def __init__(self, numcols, numrows): """ numcols is the number of columns in the grid. """ self.Text = 'DataGridView Cell Format Test' self.ClientSize = Size(800, 800) self.MinimumSize = Size(800, 800) self.dgv = DataGridView() self.numcols = numcols self.numrows = numrows self.setupdatagridview() self.adddata() self.formatheaders() # clears Windows default selection on load clearselection(self.dgv)
def __init__(self, posx, posy, height, width): """ numcols is the number of columns in the grid. """ self.Text = 'DataGridView Cell Format Test' # self.ClientSize = Size(400, 175) # self.MinimumSize = Size(height, width) # self.Height =height # self.Width =width self.ClientSize = Size(width, height) self.Location = Point(posx, posy) self.dgv = DataGridView() self.numcols = 0 self.numrows = 0 self.setupdatagridview() self.dgv.Location = Point(0, 0) self.dgv.ClientSize = Size(width, height) self.dgv.Parent = self clearselection(self.dgv) self.ToParet = None
def DataGridSetup(self): self.DataGrid = DataGridView() self.DataGrid.RowHeadersVisible = False self.DataGrid.MultiSelect = False self.DataGrid.SelectionMode = DataGridViewSelectionMode.FullRowSelect self.DataGrid.BackgroundColor = Color.FromArgb(25, 25, 25) self.DataGrid.RowsDefaultCellStyle.BackColor = Color.Silver self.DataGrid.AlternatingRowsDefaultCellStyle.BackColor = Color.Gainsboro self.DataGrid.ForeColor = Color.FromArgb(25, 25, 25) self.DataGrid.Location = Point(20, 12) self.DataGrid.Size = Size(230, 306) self.DataGrid.DataSource = self.Data() self.DataGrid.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells self.DataGrid.EditMode = DataGridViewEditMode.EditProgrammatically self.DataGrid.BorderStyle = BorderStyle.None
def __init__(self): self.Text = "Example App" self.Name = "ExampleApp" self.ClientSize = Size(370, 400) self.MinimumSize = Size(370, 300) self._table = DataTable() self._columns = { d[0]: self._table.Columns.Add(d[0], d[1]) for d in self._COLUMNS } self._loadPanel = Panel() self._loadPanel.Location = Point(0, 0) self._loadPanel.Size = Size(215, 30) self._loadPanel.Dock = DockStyle.Top self._fileTextBoxLabel = Label() self._fileTextBoxLabel.Text = "Load file" self._fileTextBoxLabel.Size = Size(100, 16) self._fileTextBoxLabel.Location = Point(5, 7) self._loadPanel.Controls.Add(self._fileTextBoxLabel) self._fileTextBox = TextBox() self._fileTextBox.Size = Size(200, 20) self._fileTextBox.Location = Point(110, 5) self._loadPanel.Controls.Add(self._fileTextBox) self._loadButton = Button() self._loadButton.Size = Size(50, 20) self._loadButton.Location = Point(315, 5) self._loadButton.Text = "Load" self._loadPanel.Controls.Add(self._loadButton) self._dataPanel = Panel() self._dataPanel.Location = Point(0, 35) self._dataPanel.Size = Size(370, 185) self._dataGrid = DataGridView() self._dataGrid.AllowUserToOrderColumns = True self._dataGrid.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize self._dataGrid.Location = Point(0, 0) self._dataGrid.Size = Size(360, 180) self._dataGrid.DataSource = self._table self._dataPanel.Controls.Add(self._dataGrid) self.Controls.Add(self._loadPanel) self.Controls.Add(self._dataPanel) self._loadButton.Click += self.loadData
def make_table(name, autosize=True): table = DataGridView() # allow user table.AllowUserToResizeColumns = False table.AllowUserToResizeRows = False table.AllowUserToAddRows = False table.AllowUserToDeleteRows = False # auto size table.AutoSize = autosize table.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill table.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells # back table.BackColor = Color.White table.BackgroundColor = Color.White # border table.BorderStyle = BorderStyle.None table.CellBorderStyle = DataGridViewCellBorderStyle.Single # column header table.ColumnHeadersVisible = True table.ColumnHeadersDefaultCellStyle.BackColor = Color.FromArgb( 238, 238, 238) table.ColumnHeadersDefaultCellStyle.Font = Font(table.Font, FontStyle.Bold) table.ColumnHeadersDefaultCellStyle.ForeColor = Color.Black table.ColumnHeadersBorderStyle = DataGridViewHeaderBorderStyle.Single # default cell table.DefaultCellStyle.SelectionBackColor = Color.White table.DefaultCellStyle.SelectionForeColor = Color.Black # dock if autosize: table.Dock = System.Windows.Forms.DockStyle.Fill # enable table.EnableHeadersVisualStyles = False # grid table.GridColor = Color.FromArgb(200, 200, 200) # select table.MultiSelect = False # name table.Name = name # row header table.RowHeadersBorderStyle = DataGridViewHeaderBorderStyle.Single table.RowHeadersDefaultCellStyle.BackColor = Color.FromArgb(240, 240, 240) table.RowHeadersDefaultCellStyle.ForeColor = Color.Empty table.RowHeadersDefaultCellStyle.SelectionBackColor = Color.Empty table.RowHeadersDefaultCellStyle.SelectionForeColor = Color.Empty table.RowHeadersVisible = False # scrolling # table.ScrollBars = ScrollBars.None # select table.SelectionMode = DataGridViewSelectionMode.FullRowSelect # top left header table.TopLeftHeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter return table
class DataGridEntry(Panel): """ Container for the DataGridView control I'm trying to test. DataGridView is customized to have row and column of mouse-over'd cell highlighted. Also, there is a customized selection color and selection limitations (one cell or one row at a time). """ def __init__(self, posx, posy, height, width): """ numcols is the number of columns in the grid. """ self.Text = 'DataGridView Cell Format Test' # self.ClientSize = Size(400, 175) # self.MinimumSize = Size(height, width) # self.Height =height # self.Width =width self.ClientSize = Size(width, height) self.Location = Point(posx, posy) self.dgv = DataGridView() self.numcols = 0 self.numrows = 0 self.setupdatagridview() self.dgv.Location = Point(0, 0) self.dgv.ClientSize = Size(width, height) self.dgv.Parent = self clearselection(self.dgv) self.ToParet = None def ClearData(self): for i in range(0, self.dgv.Rows.Count): self.dgv.Rows.Clear() for i in range(0, self.dgv.Columns.Count): self.dgv.Columns.Clear() def setupdatagridview(self): """ General construction of DataGridView control. Bind mouse events as appropriate. """ # have to have columns defined before inserting rows # self.dgv.ColumnCount = self.numcols # center all text in all data cells by default self.dgv.DefaultCellStyle.Alignment = MDDLCNTR # use Mouse events for contingency that actual # position is required # otherwise, can use events without "Mouse" # in them # CellMouseEnter event for formatting self.dgv.CellMouseEnter += self.onmouseovercell # CellMouseLeave event for formatting self.dgv.CellMouseLeave += self.onmouseleavingcell # another try at MouseClick (avoiding default select color) self.dgv.CellMouseUp += self.onmouseclickcell self.dgv.CellDoubleClick += self.cellDoubleClick # add empty rows first # for num in xrange(self.numrows): # self.dgv.Rows.Add() # format empty cells resetcellfmts(self.dgv, self.numrows) # lock control so user cannot do anything to it datawise self.dgv.AllowUserToAddRows = False self.dgv.AllowUserToDeleteRows = False self.dgv.ReadOnly = True self.dgv.ClearSelection() def formatheaders(self, headerNames=["column1", "column2", "column3"]): """ Get header row and left side column populated and formatted. """ self.numcols = len(headerNames) self.dgv.ColumnCount = self.numcols for num in xrange(self.numcols): col = self.dgv.Columns[num] col.Name = headerNames[num] col.HeaderCell.Style.Alignment = MDDLCNTR col.HeaderCell.Style.Font = BOLD col.HeaderCell.Style.ForeColor = Color.MidnightBlue self.dgv.TopLeftHeaderCell.Value = '序号' self.dgv.TopLeftHeaderCell.Style.Font = BOLD self.dgv.TopLeftHeaderCell.Style.ForeColor = Color.Blue self.dgv.RowHeadersWidth = ROWHDRWDTH def adddata(self): """ Put data into the grid, row by row, column by column. """ # self.addRowdata( "1",["1","2","3"]) # self.addRowdata( "2",["11","21","13"]) def setRowTitle(self, rowobj, rowtitle): rowobj.HeaderCell.Value = rowtitle rowobj.HeaderCell.Style.Font = BOLD rowobj.HeaderCell.Style.ForeColor = Color.Blue def addRowdata(self, rowtitle="1", datas=["1", "2", "3"]): newidx = self.dgv.Rows.Add() row = self.dgv.Rows[newidx] self.setRowTitle(row, rowtitle) dat = (datax for datax in datas) for cell in row.Cells: cell.Value = dat.next() def getcell(self, event): """ Gets DataGridViewCell that is responding to an event. Attempt to minimize code duplication by applying method to multiple events. """ colidx = event.ColumnIndex rowidx = event.RowIndex if rowidx > INDEXERROR and colidx > INDEXERROR: row = self.dgv.Rows[rowidx] cell = row.Cells[colidx] return cell else: return None def onmouseovercell(self, sender, event): return """ Change format of data cells when mouse passes over them. """ cell = self.getcell(event) rowidx, colidx = getcellidxs(event) if cell: col = self.dgv.Columns[colidx] col.HeaderCell.Style.BackColor = COLUMNCOLOR row = self.dgv.Rows[rowidx] if row.HeaderCell.Style.BackColor != SELECTCOLOR: row.HeaderCell.Style.BackColor = ROWCOLOR cell.Style.Font = BOLD if cell.Style.BackColor != SELECTCOLOR: cell.Style.BackColor = MOUSEOVERCOLOR row = self.dgv.Rows[rowidx] for cellx in row.Cells: if cellx.ColumnIndex != colidx: if cellx.Style.BackColor != SELECTCOLOR: cellx.Style.BackColor = ROWCOLOR cellx.Style.Font = BOLD for num in xrange(self.numrows): for num2 in xrange(self.numcols): if num != rowidx: if num2 == colidx: row = self.dgv.Rows[num] cell = row.Cells[num2] # 6) color all other cells in column cyan # skip selected cells if cell.Style.BackColor != SELECTCOLOR: cell.Style.BackColor = COLUMNCOLOR def onmouseleavingcell(self, sender, event): return """ Change format of data cells back to "normal" when mouse passes out of the cell. """ cell = self.getcell(event) rowidx, colidx = getcellidxs(event) if cell: resetcellfmts(self.dgv, self.numrows) resetheaderfmts(self.dgv, rowidx, colidx) clearselection(self.dgv) def onmouseclickcell(self, sender, event): return """ Attempt to override selection. """ selected = [] mockclearselection(self.dgv) cell = self.getcell(event) self.rowidx, self.colidx = getcellidxs(event) clearselection(self.dgv) if cell: cell.Style.Font = BOLD cell.Style.BackColor = SELECTCOLOR selected.append(cell.Value) if self.colidx == INDEXERROR: if self.rowidx != INDEXERROR: row = self.dgv.Rows[self.rowidx] cells = row.Cells for cell in cells: cell.Style.Font = BOLD cell.Style.BackColor = SELECTCOLOR selected.append(cell.Value) row.HeaderCell.Style.BackColor = SELECTCOLOR self.onmouseovercell(sender, event) copytoclipboard(selected) def cellDoubleClick(self, sender, event): # CellDoubleClick cell = self.getcell(event) # print( cell ) self.rowidx, self.colidx = getcellidxs(event) if self.ToParet != None and (self.rowidx != -1): rowobj = self.dgv.Rows[self.rowidx] rowtitle = rowobj.HeaderCell.Value self.ToParet(self, rowtitle) else: pass def Clear(self): self.dgv.Rows.Clear() def getCurRowObj(self): return self.dgv.Rows[self.rowidx]
class DataGridForm(Form): """ Container for the DataGridView control I'm trying to test. DataGridView is customized to have row and column of mouse-over'd cell highlighted. Also, there is a customized selection color and selection limitations (one cell or one row at a time). """ def __init__(self, numcols, numrows): """ numcols is the number of columns in the grid. """ self.Text = 'DataGridView Cell Format Test' self.ClientSize = Size(800, 800) self.MinimumSize = Size(800, 800) self.dgv = DataGridView() self.numcols = numcols self.numrows = numrows self.setupdatagridview() self.adddata() self.formatheaders() # clears Windows default selection on load clearselection(self.dgv) def setupdatagridview(self): """ General construction of DataGridView control. Bind mouse events as appropriate. """ self.dgv.Location = Point(0, 0) self.dgv.Size = Size(375, 150) self.Controls.Add(self.dgv) # have to have columns defined before inserting rows self.dgv.ColumnCount = self.numcols # center all text in all data cells by default self.dgv.DefaultCellStyle.Alignment = MDDLCNTR # use Mouse events for contingency that actual # position is required # otherwise, can use events without "Mouse" # in them # CellMouseEnter event for formatting self.dgv.CellMouseEnter += self.onmouseovercell # CellMouseLeave event for formatting self.dgv.CellMouseLeave += self.onmouseleavingcell # another try at MouseClick (avoiding default select color) self.dgv.CellMouseUp += self.onmouseclickcell # add empty rows first for num in xrange(self.numrows): self.dgv.Rows.Add() # format empty cells resetcellfmts(self.dgv, self.numrows) # lock control so user cannot do anything to it datawise self.dgv.AllowUserToAddRows = False self.dgv.AllowUserToDeleteRows = False self.dgv.ReadOnly = True self.dgv.ClearSelection() def formatheaders(self): """ Get header row and left side column populated and formatted. """ # give names to columns # if the name is the same as the desired header caption, # the Name attribute will take care of the caption for num in xrange(self.numcols): # need to center text in header row # separate from data rows col = self.dgv.Columns[num] col.Name = HEADERS[num] # slightly left of center on headers col.HeaderCell.Style.Alignment = MDDLCNTR # sets font and font style col.HeaderCell.Style.Font = BOLD col.HeaderCell.Style.ForeColor = Color.MidnightBlue # put numbers on rows for num in xrange(self.numrows): row = self.dgv.Rows[num] # get sequential numeric label on side of row row.HeaderCell.Value = str(num + 1) # sets font and font style row.HeaderCell.Style.Font = BOLD row.HeaderCell.Style.ForeColor = Color.Blue # XXX - clear button is implicit, not explicit self.dgv.TopLeftHeaderCell.Value = 'CLEAR' self.dgv.TopLeftHeaderCell.Style.Font = BOLD self.dgv.TopLeftHeaderCell.Style.ForeColor = Color.Blue self.dgv.RowHeadersWidth = ROWHDRWDTH def adddata(self): """ Put data into the grid, row by row, column by column. """ # go off indices of rows for placing data in cells for num in xrange(self.numrows): row = self.dgv.Rows[num] # iterator for data - places in correct column dat = (datax for datax in TESTDATA[num]) for cell in row.Cells: cell.Value = dat.next() def getcell(self, event): """ Gets DataGridViewCell that is responding to an event. Attempt to minimize code duplication by applying method to multiple events. """ colidx = event.ColumnIndex rowidx = event.RowIndex if rowidx > INDEXERROR and colidx > INDEXERROR: # to get a specific cell, need to first # get row the cell is in, # then get cell indexed by column row = self.dgv.Rows[rowidx] cell = row.Cells[colidx] return cell else: return None def onmouseovercell(self, sender, event): """ Change format of data cells when mouse passes over them. """ # had to separate these into two functions # problems with tuple unpacking cell = self.getcell(event) rowidx, colidx = getcellidxs(event) if cell: # 1) take care of row and column header formatting col = self.dgv.Columns[colidx] col.HeaderCell.Style.BackColor = COLUMNCOLOR row = self.dgv.Rows[rowidx] # only change if the row header is not selected if row.HeaderCell.Style.BackColor != SELECTCOLOR: row.HeaderCell.Style.BackColor = ROWCOLOR # 2) bold individual cell cell.Style.Font = BOLD # 3) color individual cell green # but skip if it is a selected cell if cell.Style.BackColor != SELECTCOLOR: cell.Style.BackColor = MOUSEOVERCOLOR row = self.dgv.Rows[rowidx] for cellx in row.Cells: # 4) color each cell in row except # green cell yellow if cellx.ColumnIndex != colidx: # skip selected cell if cellx.Style.BackColor != SELECTCOLOR: cellx.Style.BackColor = ROWCOLOR # 5) add bold to row cellx.Style.Font = BOLD # highlighting a column is harder # have to cycle through all cells for num in xrange(self.numrows): for num2 in xrange(self.numcols): # want to skip single highlighted cell if num != rowidx: if num2 == colidx: row = self.dgv.Rows[num] cell = row.Cells[num2] # 6) color all other cells in column cyan # skip selected cells if cell.Style.BackColor != SELECTCOLOR: cell.Style.BackColor = COLUMNCOLOR def onmouseleavingcell(self, sender, event): """ Change format of data cells back to "normal" when mouse passes out of the cell. """ cell = self.getcell(event) rowidx, colidx = getcellidxs(event) if cell: # need to cycle through all cells individually # to reset them resetcellfmts(self.dgv, self.numrows) resetheaderfmts(self.dgv, rowidx, colidx) clearselection(self.dgv) def onmouseclickcell(self, sender, event): """ Attempt to override selection. """ # get selected cells' data onto clipboard selected = [] mockclearselection(self.dgv) # had to separate these into two functions # problems with tuple unpacking cell = self.getcell(event) rowidx, colidx = getcellidxs(event) # overrides Windows selection color # sometimes flashes blue for a split second clearselection(self.dgv) # if dealing with one valid data cell (not header) if cell: cell.Style.Font = BOLD cell.Style.BackColor = SELECTCOLOR selected.append(cell.Value) # if a row header is clicked, select row if colidx == INDEXERROR: # need to make sure that upper left header is not clicked if rowidx != INDEXERROR: row = self.dgv.Rows[rowidx] cells = row.Cells # highlight all the cells in the row for cell in cells: cell.Style.Font = BOLD cell.Style.BackColor = SELECTCOLOR selected.append(cell.Value) # highlight the row header row.HeaderCell.Style.BackColor = SELECTCOLOR # get mouseover coloration reset self.onmouseovercell(sender, event) copytoclipboard(selected)
class DataGridEntry(Panel): """ Container for the DataGridView control I'm trying to test. DataGridView is customized to have row and column of mouse-over'd cell highlighted. Also, there is a customized selection color and selection limitations (one cell or one row at a time). """ def __init__(self, posx, posy, height, width): """ numcols is the number of columns in the grid. """ self.Text = 'DataGridView Cell Format Test' # self.ClientSize = Size(400, 175) # self.MinimumSize = Size(height, width) # self.Height =height # self.Width =width self.ClientSize = Size(width, height) self.Location = Point(posx, posy) self.dgv = DataGridView() self.numcols = 0 self.numrows = 0 self.setupdatagridview() self.dgv.Location = Point(0, 0) self.dgv.ClientSize = Size(width, height) self.dgv.Parent = self # clearselection(self.dgv) self.ToParet = None self.dgv.Font = getFont() # print( self.dgv.Font ) def ClearData(self): for i in range(0, self.dgv.Rows.Count): self.dgv.Rows.Clear() for i in range(0, self.dgv.Columns.Count): self.dgv.Columns.Clear() def setupdatagridview(self): """ General construction of DataGridView control. Bind mouse events as appropriate. """ # have to have columns defined before inserting rows # self.dgv.ColumnCount = self.numcols # center all text in all data cells by default self.dgv.DefaultCellStyle.Alignment = MDDLCNTR # use Mouse events for contingency that actual # position is required # otherwise, can use events without "Mouse" # in them # CellMouseEnter event for formatting self.dgv.CellMouseEnter += self.onmouseovercell # CellMouseLeave event for formatting self.dgv.CellMouseLeave += self.onmouseleavingcell # another try at MouseClick (avoiding default select color) self.dgv.CellMouseUp += self.onmouseclickcell self.dgv.CellDoubleClick += self.cellDoubleClick # add empty rows first # for num in xrange(self.numrows): # self.dgv.Rows.Add() # format empty cells resetcellfmts(self.dgv, self.numrows) # lock control so user cannot do anything to it datawise self.dgv.AllowUserToAddRows = False self.dgv.AllowUserToDeleteRows = False self.dgv.ReadOnly = True self.dgv.ClearSelection() # self.dgv.VirtualMode =True self.ctxMenuStripInit() # self.dgv.CellContextMenuStripNeeded += self.contextMenuShow def formatheaders(self, headerNames=["column1", "column2", "column3"]): """ Get header row and left side column populated and formatted. """ self.numcols = len(headerNames) self.dgv.ColumnCount = self.numcols for num in xrange(self.numcols): col = self.dgv.Columns[num] col.Name = headerNames[num] col.HeaderCell.Style.Alignment = MDDLCNTR col.HeaderCell.Style.Font = getFont() col.HeaderCell.Style.ForeColor = Color.MidnightBlue self.dgv.TopLeftHeaderCell.Value = '序号' self.dgv.TopLeftHeaderCell.Style.Alignment = MDDLCNTR self.dgv.TopLeftHeaderCell.Style.Font = getFont() self.dgv.TopLeftHeaderCell.Style.ForeColor = Color.Red self.dgv.RowHeadersWidth = ROWHDRWDTH def adddata(self): """ Put data into the grid, row by row, column by column. """ # self.addRowdata( "1",["1","2","3"]) # self.addRowdata( "2",["11","21","13"]) def setRowTitle(self, rowobj, rowtitle): rowobj.HeaderCell.Style.Alignment = MDDLCNTR rowobj.HeaderCell.Style.Font = getFont() rowobj.HeaderCell.Style.ForeColor = Color.Red rowobj.HeaderCell.Value = rowtitle # print(rowobj.HeaderCell.Value ,rowobj.HeaderCell.Style.Font, MDDLCNTR ) def addRowdata(self, rowtitle="1", datas=["1", "2", "3"]): # print("addRowdata" ) newidx = self.dgv.Rows.Add() row = self.dgv.Rows[newidx] self.setRowTitle(row, rowtitle) dat = (datax for datax in datas) for cell in row.Cells: cell.Value = dat.next() setcellfmts(self.dgv, row) def getcell(self, event): """ Gets DataGridViewCell that is responding to an event. Attempt to minimize code duplication by applying method to multiple events. """ colidx = event.ColumnIndex rowidx = event.RowIndex if rowidx > INDEXERROR and colidx > INDEXERROR: row = self.dgv.Rows[rowidx] cell = row.Cells[colidx] return cell else: return None def onmouseovercell(self, sender, event): return def onmouseleavingcell(self, sender, event): return """ Change format of data cells back to "normal" when mouse passes out of the cell. """ def onmouseclickcell(self, sender, event): return """ Attempt to override selection. """ # selected = [] # mockclearselection(self.dgv) # cell = self.getcell(event) # self.rowidx, self.colidx = getcellidxs(event) # clearselection(self.dgv) # if cell: # cell.Style.Font = BOLD # cell.Style.BackColor = SELECTCOLOR # selected.append(cell.Value) # if self.colidx == INDEXERROR: # if self.rowidx != INDEXERROR: # row = self.dgv.Rows[self.rowidx] # cells = row.Cells # for cell in cells: # cell.Style.Font = BOLD # cell.Style.BackColor = SELECTCOLOR # selected.append(cell.Value) # row.HeaderCell.Style.BackColor = SELECTCOLOR # self.onmouseovercell(sender, event) # copytoclipboard(selected) def cellDoubleClick(self, sender, event): # CellDoubleClick cell = self.getcell(event) # print( cell ) self.rowidx, self.colidx = getcellidxs(event) if self.ToParet != None and (self.rowidx != -1): rowobj = self.dgv.Rows[self.rowidx] rowtitle = rowobj.HeaderCell.Value self.ToParet(self, rowtitle) # print("To Parent Proc") else: pass def Clear(self): self.dgv.Rows.Clear() def getCurRowObj(self): return self.dgv.Rows[self.rowidx] ######################################################################################### def ctxMenuStripInit(self): self.ctxMenuStrip = ContextMenuStrip() # ### Attach an event handler for the # ### ContextMenuStrip control's Opening event. self.ctxMenuStrip.Opening += System.ComponentModel.CancelEventHandler( self.cms_Opening) self.dgv.ContextMenuStrip = self.ctxMenuStrip def cms_Opening(self, sender, eventArg): ### Acquire references to the owning control and item. self.srcControl = self.ctxMenuStrip.SourceControl #as Control; tsi = self.ctxMenuStrip.OwnerItem #as ToolStripDropDownItem; ### Clear the ContextMenuStrip control's Items collection. self.ctxMenuStrip.Items.Clear() ### Check the source control first. if (self.srcControl != None): ### Add custom item (Form) self.ctxMenuStrip.Items.Add( "Source Control: " + str(type(self.srcControl))) #srcControl.GetType().ToString()); elif (tsi != None): ### Add custom item (ToolStripDropDownButton or ToolStripMenuItem) self.ctxMenuStrip.Items.Add("Owner : " + str(type(tsi))) ### Populate the ContextMenuStrip control with its default items. self.ctxMenuStrip.Items.Add("-") ts1 = fontToolStripMenuItem("Copy Selected to Clipboard", None, self.selectionToClip) self.ctxMenuStrip.Items.Add(ts1) ts1 = fontToolStripMenuItem("Copy All seleted Rows to Clipboard", None, self.selectionRowToClip) self.ctxMenuStrip.Items.Add(ts1) ts1 = fontToolStripMenuItem("Copy All seleted Columns to Clipboard", None, self.selectionColToClip) self.ctxMenuStrip.Items.Add(ts1) ts1 = fontToolStripMenuItem("Copy All Table to Clipboard", None, self.tblToClip) self.ctxMenuStrip.Items.Add(ts1) title = "所选行的金额之和到剪贴板" v = self.sumRowsValue("金额") vstr = "{: ,.6f}".format(v) ts1 = fontToolStripMenuItem(title + ": " + vstr, None, self.sumToClip) self.ctxMenuStrip.Items.Add(ts1) eventArg.Cancel = False def sumRowsValue(self, sumField): sum = 0.0 rowsRec = [] for cell in self.dgv.SelectedCells: rowobj = cell.OwningRow.Cells if rowobj in rowsRec: continue else: rowsRec += [rowobj] for col in rowobj: name = col.OwningColumn.HeaderText # HeaderCell.Value # print( name ) if sumField in name: value = col.Value.strip().replace(",", "") try: sum += float(value) except: pass return sum def sumToClip(self, sender, event): print(self.srcControl, sender, event) v = self.sumRowsValue("金额") vstr = '"{: ,.6f}"'.format(v) cp2Clipboard(vstr) def selectionToClip(self, sender, event): selects = dict() for cell in self.dgv.SelectedCells: oRow = cell.OwningRow.Index oCol = cell.OwningColumn.Index value = cell.Value.replace('"', "'") vstr = '"{}"'.format(value) selects[(oRow, oCol)] = vstr ks = sorted(selects.keys()) r0 = -1 vstr = "" for r, c in ks: r0 = r break for r, c in ks: if r == r0: title = self.dgv.Columns[c].HeaderText vstr += title.replace(",", ";") + "," else: break # vstr +="\n" r0 = -1 for r, c in ks: if r != r0: vstr += "\n" r0 = r vstr += selects[(r, c)] + "," cp2Clipboard(vstr) def selectionRowToClip(self, sender, event): print("selectionToClip") rows = [] for cell in self.dgv.SelectedCells: if cell.OwningRow in rows: continue else: rows += [ cell.OwningRow, ] # print(cell.Value,cell.ColumnIndex ,cell.RowIndex,cell.OwningRow) if len(rows) == 0: return vstr = "" for cell in rows[0].Cells: title = cell.OwningColumn.HeaderText vstr += title.replace(",", ";") + "," for i in range(0, len(rows)): vstr += "\n" for cell in rows[i].Cells: value = cell.Value.replace('"', "'") vstr += '"{}",'.format(value) cp2Clipboard(vstr) def selectionColToClip(self, sender, event): self.selectionRowToClip(sender, event) def tblToClip(self, sender, event): vstr = "" for col in self.dgv.Columns: title = col.HeaderText vstr += title.replace(",", ";") + "," for rowobj in self.dgv.Rows: vstr += "\n" for cell in rowobj.Cells: value = cell.Value.replace('"', "'") vstr += '"{}",'.format(value) cp2Clipboard(vstr)
def __init__(self, ref_obj): super(RevitPythonHelper, self).__init__() self.ref_obj = ref_obj self.filter_sys_memb = True self.Size = Size(650, 800) self.Text = 'Explorer' self.tooltips = ToolTip() self.StartPosition = FormStartPosition.Manual # self.Location = Point(600,0) # to display in your favorite corner self.panright = SplitContainer() self.panright.Parent = self self.panright.Dock = DockStyle.Fill self.panright.Orientation = Orientation.Horizontal self.panright.SplitterDistance = 100 self.top_info = RichTextBox() self.top_info.Dock = DockStyle.Fill self.top_info.DetectUrls = True self.table = DataGridView() self.table.Dock = DockStyle.Fill self.table.RowHeadersVisible = False self.table.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCellsExceptHeaders self.table.RowTemplate.Height = 30 self.table.SelectionMode = DataGridViewSelectionMode.RowHeaderSelect self.table.DefaultCellStyle.WrapMode = DataGridViewTriState. True self.table.DefaultCellStyle.BackColor = Color.GhostWhite self.table.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter col1 = DataGridViewTextBoxColumn() col1.HeaderText = 'Name' col1.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill col1.FillWeight = 20 col1.DefaultCellStyle.Font = Font(self.table.DefaultCellStyle.Font, FontStyle.Underline) col2 = DataGridViewTextBoxColumn() col2.HeaderText = 'Type' col2.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill col2.FillWeight = 5 col2.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter col3 = DataGridViewTextBoxColumn() col3.HeaderText = 'Value' col3.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill col3.FillWeight = 15 col4 = DataGridViewTextBoxColumn() col4.HeaderText = 'Infos' col4.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill col4.FillWeight = 60 self.table.Columns.AddRange((col1, col2, col3, col4)) self.table.AutoGenerateColumns = False self.panright.Panel1.Controls.Add(self.top_info) self.panright.Panel2.Controls.Add(self.table) self.panright.FixedPanel = FixedPanel.Panel1 self.toolpan = FlowLayoutPanel() self.toolpan.Parent = self self.toolpan.Dock = DockStyle.Top self.toolpan.Height = 25 self.check = CheckBox() self.check.Parent = self.toolpan self.check.Text = "Hide Sys" self.check.Checked = True self.close = Button() self.close.Parent = self self.close.Dock = DockStyle.Bottom self.close.Text = 'Close' self.close.Height = 30 # LOAD DATAS self.update_info(extract_main(self.ref_obj)) self.update_table(extract_members(self.ref_obj, self.filter_sys_memb)) self.Show() # EVENTS self.top_info.LinkClicked += self.on_link_clicked self.check.CheckedChanged += self.on_hide_member_clicked self.close.Click += self.on_close self.table.MouseEnter += self.get_focus self.table.CellContentDoubleClick += self.on_val_double_click
class RevitPythonHelper(Form): ''' ''' def __init__(self, ref_obj): super(RevitPythonHelper, self).__init__() self.ref_obj = ref_obj self.filter_sys_memb = True self.Size = Size(650, 800) self.Text = 'Explorer' self.tooltips = ToolTip() self.StartPosition = FormStartPosition.Manual # self.Location = Point(600,0) # to display in your favorite corner self.panright = SplitContainer() self.panright.Parent = self self.panright.Dock = DockStyle.Fill self.panright.Orientation = Orientation.Horizontal self.panright.SplitterDistance = 100 self.top_info = RichTextBox() self.top_info.Dock = DockStyle.Fill self.top_info.DetectUrls = True self.table = DataGridView() self.table.Dock = DockStyle.Fill self.table.RowHeadersVisible = False self.table.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCellsExceptHeaders self.table.RowTemplate.Height = 30 self.table.SelectionMode = DataGridViewSelectionMode.RowHeaderSelect self.table.DefaultCellStyle.WrapMode = DataGridViewTriState. True self.table.DefaultCellStyle.BackColor = Color.GhostWhite self.table.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter col1 = DataGridViewTextBoxColumn() col1.HeaderText = 'Name' col1.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill col1.FillWeight = 20 col1.DefaultCellStyle.Font = Font(self.table.DefaultCellStyle.Font, FontStyle.Underline) col2 = DataGridViewTextBoxColumn() col2.HeaderText = 'Type' col2.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill col2.FillWeight = 5 col2.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter col3 = DataGridViewTextBoxColumn() col3.HeaderText = 'Value' col3.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill col3.FillWeight = 15 col4 = DataGridViewTextBoxColumn() col4.HeaderText = 'Infos' col4.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill col4.FillWeight = 60 self.table.Columns.AddRange((col1, col2, col3, col4)) self.table.AutoGenerateColumns = False self.panright.Panel1.Controls.Add(self.top_info) self.panright.Panel2.Controls.Add(self.table) self.panright.FixedPanel = FixedPanel.Panel1 self.toolpan = FlowLayoutPanel() self.toolpan.Parent = self self.toolpan.Dock = DockStyle.Top self.toolpan.Height = 25 self.check = CheckBox() self.check.Parent = self.toolpan self.check.Text = "Hide Sys" self.check.Checked = True self.close = Button() self.close.Parent = self self.close.Dock = DockStyle.Bottom self.close.Text = 'Close' self.close.Height = 30 # LOAD DATAS self.update_info(extract_main(self.ref_obj)) self.update_table(extract_members(self.ref_obj, self.filter_sys_memb)) self.Show() # EVENTS self.top_info.LinkClicked += self.on_link_clicked self.check.CheckedChanged += self.on_hide_member_clicked self.close.Click += self.on_close self.table.MouseEnter += self.get_focus self.table.CellContentDoubleClick += self.on_val_double_click #self.table.SortCompare += self.sort_by_name # TODO double sort def update_info(self, text): '''Display main info in the richtextbox arg : text as string ''' self.top_info.Text = text self.top_info.SelectionStart = 0 self.top_info.SelectionLength = len(self.top_info.Text.split('\n')[0]) self.top_info.SelectionFont = Font(self.top_info.Font, FontStyle.Bold) self.top_info.SelectionLength = 0 def update_table(self, sourcelist): '''Populate listview with selected member or group arg: a list of tuples (member, type, val, docstring) ''' self.table.Rows.Clear() self.table.SuspendLayout() for member, mtype, val, doc in sourcelist: self.table.Rows.Add(member, mtype, val, doc) self.table.ResumeLayout() def on_close(self, sender, event): '''Get out! ''' self.Close() def on_link_clicked(self, sender, event): ''' Open tab in default browser ''' webbrowser.open_new_tab(event.LinkText) def on_hide_member_clicked(self, sender, event): ''' Update views to hide/show object base members ''' self.filter_sys_memb = sender.Checked self.update_table(extract_members(self.ref_obj, self.filter_sys_memb)) def on_val_double_click(self, sender, event): ''' Open a new form to display clicked member ''' try: if event.ColumnIndex == 0: member = sender.Rows[event.RowIndex].Cells[ event.ColumnIndex].Value new_ref = getattr(self.ref_obj, member) RevitPythonHelper(new_ref) except: print("Can't reach this reference") def get_focus(self, sender, event): '''Add convenient focus for scroll in datagrid ''' if not sender.Focused: sender.Focus() def sort_by_name(self, sender, event): ''' Overide the automatic grid sort ''' event.SortResult = System.String.Compare(event.CellValue1.ToString(), event.CellValue2.ToString()) if not (event.SortResult and event.Column.Index == 0): event.SortResult = System.String.Compare( sender.Rows[event.RowIndex1].Cells[0].Value.ToString(), sender.Rows[event.RowIndex2].Cells[0].Value.ToString()) event.Handled = True
def setupDataGridView(self): self._dataGridView1 = DataGridView() self._dataGridView1.AllowUserToOrderColumns = True self._dataGridView1.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize self._dataGridView1.Dock = DockStyle.Fill self._dataGridView1.Location = Point(0, 111) self._dataGridView1.Size = Size(506, 273) self._dataGridView1.TabIndex = 3 self._dataGridView1.ColumnCount = len(headers) self._dataGridView1.ColumnHeadersVisible = True for i in range(len(headers)): self._dataGridView1.Columns[i].Name = headers[i] for j in range(len(signals)): for k in range(len(headers)): array_str[k] = signals[j][k] self._dataGridView1.Rows.Add(array_str) self.Controls.Add(self._dataGridView1) #Application.Run(DataGridViewQueryForm())