DataGridView very detailed usage (reproduced)

Source: Internet
Author: User
Tags border color rowcount

One
DataGridView Gets or modifies the contents of the current cell:
The current cell refers to the cell in which the DataGridView focus is located, which can be obtained through the CurrentCell property of the DataGridView object. Returns Nothing if the current cell does not exist (C # is NULL)
Get current cell contents
Console.WriteLine (DataGridView1.CurrentCell.Value);
Gets the column of the current cell Index
Console.WriteLine (DataGridView1.CurrentCell.ColumnIndex);
Gets the row Index of the current cell
Console.WriteLine (DataGridView1.CurrentCell.RowIndex);
Also, use the Datagridview.currentcelladdress property instead of directly accessing the cell to determine the row in which the cell is located: Datagridview.currentcelladdress.y and columns: Datagridview.currentcelladdress.x. This is useful for avoiding sharing shared rows.
The current cell can be changed by setting the CurrentCell of the DataGridView object. Can be set by CurrentCell.
The active cell of the DataGridView. Set CurrentCell to Nothing (null) to deactivate the cell.
Setting (0, 0) is the current cell
Datagridview1.currentcell = datagridview1[0, 0];
You can also set the selected row by CurrentCell when the entire row is checked.
/**////

Traverse down
///

///
///
private void Button4_Click (object sender, EventArgs e)
... {
int row = This.dataGridView1.CurrentRow.Index + 1;
if (Row > This.datagridview1.rowcount-1)
row = 0;
This.dataGridView1.CurrentCell = this.datagridview1[0, row];
}

/**////

Traverse up
///

///
///
private void Button5_click (object sender, EventArgs e)
... {
int row = this.datagridview1.currentrow.index-1;
if (Row < 0)
row = this.datagridview1.rowcount-1;
This.dataGridView1.CurrentCell = this.datagridview1[0, row];
}
* Note: The parameters of the This.datagridview indexer are: columnindex, RowIndex or ColumnName, RowIndex
This is different from the habit.
②datagridview Set Cell read-only:
1) using the ReadOnly property
? If you want all cells in the DataGridView to be non-editable, simply:
[C #]
Set DataGridView1 to read-only
Datagridview1.readonly = true;
At this point, the user's new row and delete row operations are also masked.
? If you want a cell in the DataGridView to be non-editable, simply:
[C #]
Set the 2nd column of the DataGridView1 column to be read-only
DATAGRIDVIEW1.COLUMNS[1]. ReadOnly = true;
Sets the 3rd row of DataGridView1 for the entire row of cells to be read-only
DATAGRIDVIEW1.ROWS[2]. ReadOnly = true;
Set DataGridView1 [0,0] cell as read-only
Datagridview1[0, 0]. ReadOnly = true;
2) using the EditMode property
When the Datagridview.editmode property is set to Datagridvieweditmode.editprogrammatically, the user cannot edit the contents of the cell manually. However, you can use the program to invoke the Datagridview.beginedit method to make the cell enter edit mode for editing.
[C #]
Datagridview1.editmode = datagridvieweditmode.editprogrammatically;
3) Set the non-editable state of the cell according to the conditions
When one of the ways to set cell ReadOnly properties by cell coordinates is too cumbersome, you can cancel the cell edits by Cellbeginedit the event.
[C #]
Cellbeginedit Event Handling method
private void Datagridview1_cellbeginedit (object sender,
DataGridViewCellCancelEventArgs e)
{
DataGridView DGV = (DataGridView) sender;
Whether the conditional check can be edited
if (DGV. Columns[e.columnindex]. Name = = "Column1" &&
! (bool) dgv["Column2", E.rowindex]. Value)
{
Cancel Edit
E.cancel = true;
}
}
Two
DataGridView does not display the following new line:
Usually the bottom line of the DataGridView is the user's newly added line (wardrobe display *). You can set the Allowusertoaddrows property of the DataGridView object to False if you do not want the new row to appear when the user appends the new row.
[C #]
Set user cannot manually add new lines to DataGridView1
Datagridview1.allowusertoaddrows = false;
However, you can append a new line to DataGridView by using the program: Datagridviewrowcollection.add.
Top up: If the DataGridView DataSource is bound to DataView, you can also set the Dataview.allowadd
property to False to achieve the same effect.
④datagridview Judging new rows:
DataGridView's Allowusertoaddrows property is true when the user is allowed to append a new row, the last line of the DataGridView is the newly appended row (* row). Use the Datagridviewrow.isnewrow property to determine which line is the newly appended row. In addition, the row sequence number of the new row can be obtained by Datagridview.newrowindex. In the absence of a new line, Newrowindex =-1.
⑤datagridview customization of the user delete operation for the row:
1) unconditionally restrict the row deletion operation.
By default, DataGridView is the one that allows the user to delete rows. If the Allowusertodeleterows property of the DataGridView object is set to False, the user's row delete operation is disabled.
[C #]
Disables DataGridView1 of the row delete operation.
Datagridview1.allowusertodeleterows = false;
However, it is possible to delete rows by Datagridviewrowcollection.remove.
Top up: If DataGridView binds to DataView, the deletion of rows can also be controlled by Dataview.allowdelete.
2) The Condition judgment processing when the row is deleted.
When a user deletes a row, the Datagridview.userdeletingrow event is raised. In this event, you can determine the condition and cancel the delete operation.
[C #]
DataGridView1 's Userdeletingrow Event
private void Datagridview1_userdeletingrow (
Object sender, Datagridviewrowcanceleventargs e)
{
User acknowledgement prior to deletion.
if (MessageBox.Show ("Confirm that you want to delete the row data?") "," Delete Confirmation ",
Messageboxbuttons.okcancel,
messageboxicon.question)! = DialogResult.OK)
{
If it is not OK, cancel.
E.cancel = true;
}
}
⑥datagridview and deleting rows and columns:
1) row, column hide
[C #]
DataGridView1 's first column hides
Datagridview1.columns[0]. Visible = false;
The first line of DataGridView1 is hidden
Datagridview1.rows[0]. Visible = false;
2) Wardrobe, column head of the hidden
[C #]
Column header Hidden
Datagridview1.columnheadersvisible = false;
Wardrobe Hidden
Datagridview1.rowheadersvisible = false;
3) Deletion of rows and columns
[C #]
' Delete the column named ' Column1 '
DataGridView1.Columns.Remove ("Column1");
' Delete the first column
DataGridView1.Columns.RemoveAt (0);
' Delete the first row
DataGridView1.Rows.RemoveAt (0);
4) Delete the selected row
[C #]
foreach (DataGridViewRow R in Datagridview1.selectedrows)
{
if (!r.isnewrow)
{
DataGridView1.Rows.Remove (R);
}
}
⑦datagridview Resize to prohibit columns or rows:
1) Prohibit all columns or rows of resize
[C #]
Prevents users from changing the column widths of all DataGridView1 columns
Datagridview1.allowusertoresizecolumns = false;
Prevents users from changing the row height of all datagridview1の rows
Datagridview1.allowusertoresizerows = false;
However, column widths and row heights can be set by Datagridviewcolumn.width or Datagridviewrow.height properties.
2) prohibit the resize of the specified row or column
[C #]
Prevents users from changing the column width of the first row of DataGridView1
Datagridview1.columns[0]. resizable = Datagridviewtristate.false;
Prevents users from changing the line width of the first column of DataGridView1
Datagridview1.rows[0]. resizable = Datagridviewtristate.false;
? About Noset
When the resizable property is set to Datagridviewtristate.notset, it will actually default to DataGridView Allowusertoresizecolumns and Allowusertoresizerows The property value is set. For example: Datagridview.allowusertoresizecolumns = False and resizable is noset set, resizable = False.
Determines whether resizable is inherited by setting the attribute values of DataGridView allowusertoresizecolumns and Allowusertoresizerows, which can be judged according to the State property. If the state property contains Resizableset, then there is no inheritance setting.
3) The setting of the minimum value of column width and row height
[C #]
The minimum column width for the first column is set to 100
Datagridview1.columns[0]. Minimumwidth = 100;
The minimum row height of the first row is set to 50
Datagridview1.rows[0]. Minimumheight = 50;
4) prevents the user from changing the width of the wardrobe and the height of the column head
[C #]
Prohibit user from changing column header height
Datagridview1.columnheadersheightsizemode =
datagridviewcolumnheadersheightsizemode.disableresizing;
Prevent users from changing the width of the wardrobe
Datagridview1.rowheaderswidthsizemode =
datagridviewrowheaderswidthsizemode.enableresizing;

Three
⑨datagridview Freezing columns or rows
1) Column freeze
When the Datagridviewcolumn.frozen property is True, all the columns to the left of the column are pinned, and the fixed column does not scroll around with the scrollbar while scrolling horizontally. This is useful for fixed display of important columns.
[C #]
DataGridView1 left 2-column fixed
DATAGRIDVIEW1.COLUMNS[1]. Frozen = true;
However, when datagridview.allowusertoordercolumns = True, fixed columns cannot be moved to non-fixed columns, and vice versa.
2) Line freeze
When the Datagridviewrow.frozen property is True, all rows above the row are pinned, and the fixed row moves up or down without scrolling with the scroll bar when scrolling vertically.
[C #]
DataGridView1 3-row fixed
DATAGRIDVIEW1.ROWS[2]. Frozen = true;
⑩datagridview Adjustment of column order
When setting DataGridView's allowusertoordercolumns to True, the user is free to adjust the order of the columns.
When the user changes the order of the columns, its own Index does not change, but the displayindex changes. You can also change the order of the columns by changing the DisplayIndex in the program. The Columndisplayindexchanged event is raised when the column order changes:
[C #]
Columndisplayindexchanged event handling method for DataGridView1
private void Datagridview1_columndisplayindexchanged (object sender,
DataGridViewColumnEventArgs e)
{
Console.WriteLine ("{0} 's position changed to {1}",
E.column.name, E.column.displayindex);
}
? DataGridView the cell of the head of a costume column
[C #]
Change the first column header contents of DataGridView1
Datagridview1.columns[0]. Headercell.value = "first column";
Change DataGridView1 's first line of the outfit content
Datagridview1.rows[0]. Headercell.value = "First line";
Change the contents of DataGridView1 's upper left-hand header unit
DataGridView1.TopLeftHeaderCell.Value = "upper left";
Alternatively, you can change their content by HeaderText.
[C #]
Change the first column header contents of DataGridView1
Datagridview1.columns[0]. HeaderText = "first column";
? Operation of the DataGridView shear plate
When the Datagridview.clipboardcopymode property is set to a condition other than datagridviewclipboardcopymode.disable, "ctrl + When the c"is pressed, the contents of the selected cell are copied to the system Clipboard. The formats are: Text, unicodetext,html, Commaseparatedvalue. You can paste directly into Excel.
Clipboardcopymode can also set whether the header part is copied: Enablealwaysincludeheadertext Copy header section, Enablewithoutheadertext is not copied. The default is Enablewithautoheadertext, and if the Header is selected, it is copied.
1) A copy of the Clipboard by way of programming
Clipboard.setdataobject (Datagridview1.getclipboardcontent ())
2) DataGridView Data paste
It is easier to make copies of the Clipboard, but it is more difficult to achieve DataGridView direct pasting. "ctrl + v" Press to paste, DataGridView not provide methods, can only be implemented by themselves.
The following is a simple case code for pasting, which pastes the copied data into the area starting with the selection cell.
[C #]
Determines whether the current cell is selected
if (Datagridview1.currentcell = = null)
Return
int insertrowindex = DataGridView1.CurrentCell.RowIndex;
Get the contents of the Clipboard and split by row
String pastetext = Clipboard.gettext ();
if (string. IsNullOrEmpty (Pastetext))
Return
Pastetext = Pastetext.replace ("", "");
Pastetext = Pastetext.replace (",");
Pastetext.trimend (new char[] {"});
String[] lines = Pastetext.split (");
bool IsHeader = true;
foreach (string line in lines)
{
Whether it is a column header
if (IsHeader)
{
IsHeader = false;
Continue
}
Split data by Tab
string[] Vals = line. Split (');
Determine whether the number of columns is uniform
if (Vals. Length-1! = datagridview1.columncount)
throw new ApplicationException ("The number of pasted columns is incorrect. ");
DataGridViewRow row = Datagridview1.rows[insertrowindex];
Wardrobe Settings
Row. Headercell.value = Vals[0];
Cell Content Settings
for (int i = 0; i < row. Cells.count; i++)
{
Row. Cells.value = vals[i + 1];
}
Row index of DataGridView +1
insertrowindex++;
}
? DataGridView setting of the ToolTip for cell
Datagridview.showcelltooltips = True, the ToolTip of the cell can be represented. For cells that are narrow and cannot be fully displayed, the TOOLTIP can display the necessary information.
1) Set the tooltip content of the cell
[C #]
Set the tooltip content for a cell
Datagridview1[0, 0]. ToolTipText = "The contents of this cell cannot be modified";
Set the tooltip contents of a column header cell
Datagridview1.columns[0]. ToolTipText = "The column can only enter numbers";
Set the tooltip content of the cell for the wardrobe
Datagridview1.rows[0]. Headercell.tooltiptext = "The cell contents of this row cannot be modified";
2) celltooltiptextneeded Event
The celltooltiptextneeded event can be used when the ToolTip of a batch cell is set to a lower efficiency than the one specified. This event is also raised when the cell's tooltiptext changes. However, when DataGridView's datasource is specified and Virualmode=true, the event is not raised.
[C #]
Celltooltiptextneeded Event Handling method
private void Datagridview1_celltooltiptextneeded (object sender,
Datagridviewcelltooltiptextneededeventargs e)
{
E.tooltiptext = e.columnindex.tostring () + "," + e.rowindex.tostring ();
}
? DataGridView Right-click menu (ContextMenuStrip)
DataGridView, DataGridViewColumn, DataGridViewRow, DataGridViewCell have ContextMenuStrip properties. You can control the display of the right-click menu of the DataGridView by setting the ContextMenuStrip object. The ContextMenuStrip property of DataGridViewColumn sets the right-click menu for cells other than column headers. DataGridViewRow's ContextMenuStrip property sets the right-click menu for cells other than the wardrobe. The DataGridViewCell ContextMenuStrip property sets the right-click menu for the specified cell.
[C #]
ContextMenuStrip Settings for DataGridView
Datagridview1.contextmenustrip = this. CONTEXTMENUSTRIP1;
ContextMenuStrip Settings for columns
Datagridview1.columns[0]. ContextMenuStrip = this. CONTEXTMENUSTRIP2;
ContextMenuStrip setting of the column header
Datagridview1.columns[0]. Headercell.contextmenustrip = this. CONTEXTMENUSTRIP2;
ContextMenuStrip setting of the line
Datagridview1.rows[0]. ContextMenuStrip = this. CONTEXTMENUSTRIP3;
ContextMenuStrip Settings for cells
Datagridview1[0, 0]. ContextMenuStrip = this. CONTEXTMENUSTRIP4;
For the settings of the right-click menu on the cell, the priority is: cell > Row > Column > DataGridView
? cellcontextmenustripneeded, rowcontextmenustripneeded Events
The Cellcontextmenustripneeded event allows you to set the right-click menu for a cell, especially if the right-click menu changes depending on the cell value. Using this event to set the right-click menu is more efficient than using loop traversal. However, the event will not be raised when DataGridView uses the DataSource binding and is VirtualMode.
[C #]
Cellcontextmenustripneeded Event Handling method
private void Datagridview1_cellcontextmenustripneeded (object sender,
DataGridViewCellContextMenuStripNeededEventArgs e)
{
DataGridView DGV = (DataGridView) sender;
if (E.rowindex < 0)
{
ContextMenuStrip setting of the column header
E.contextmenustrip = this. CONTEXTMENUSTRIP1;
}
else if (E.columnindex < 0)
{
ContextMenuStrip setting of the costume
E.contextmenustrip = this. CONTEXTMENUSTRIP2;
}
else if (Dgv[e.columnindex, E.rowindex]. Value is int)
{
If the cell value is an integer
E.contextmenustrip = this. CONTEXTMENUSTRIP3;
}
}
Similarly, you can set the right-click menu for a row by using the Rowcontextmenustripneeded event. [C #]
Rowcontextmenustripneeded Event Handling method
private void Datagridview1_rowcontextmenustripneeded (object sender,
Datagridviewrowcontextmenustripneededeventargs e)
{
DataGridView DGV = (DataGridView) sender;
When the "Column1" column is of type bool and true, set its ContextMenuStrip
Object boolval = dgv["Column1", E.rowindex]. Value;
Console.WriteLine (Boolval);
if (Boolval is bool && (BOOL) boolval)
{
E.contextmenustrip = this. CONTEXTMENUSTRIP1;
}
}
Cellcontextmenustripneeded event handling methods in the parameters, "e.columnindex=-1" represents the Wardrobe, "e.rowindex=-1" represents the column header. rowcontextmenustripneeded There is no "e.rowindex=-1" situation.
? DataGridView the border of a cell, the grid line style setting
1) setting of the DataGridView border line style
The style of the DataGridView border line is set by the Datagridview.borderstyle property. The BorderStyle property setting value is a
BorderStyle enumeration: FixedSingle (single line, default), Fixed3D, None.
2) Setting the border line style of the cell
The style of the cell's border line is set by the Datagridview.cellborderstyle property. The Cellborderstyle property setting value is
Datagridviewcellborderstyle enumeration. (see MSDN for details)
In addition, the Datagridview.columnheadersborderstyle and Rowheadersborderstyle properties allow you to modify the cell border line style of the DataGridView's head. The property setting value is the Datagridviewheaderborderstyle enumeration. (see MSDN for details)
3) Setting the border color of the cell
The color of the cell's border line can be set by the Datagridview.gridcolor property. The default is Controldarkdark. However, the color of the border line can only be changed if the Cellborderstyle is set to single, Singlehorizontal, singlevertical. Similarly, Columnheadersborderstyle and rowheadersborderstyle can change colors only when they are set to single.
4) separate settings for the top and bottom border lines of the cell
Cellborderstyle can only set the style of all the border lines of the cell. To change the style of one side border of a cell individually, you need to use the Datagridview.advancedcellborderstyle property. As an example:
Similarly, the properties for setting the Wardrobe cell are: Advancedrowheadersborderstyle, and the Set column header cell property is: Advancedcolumnheadersborderstyle.
? DataGridView cell represents a custom value
With the Cellformatting event, you can customize the cell's representation value. (for example, when the value is error, the cell is set to red)
The following example: Change the value of the "Colmn1" column to uppercase.
[C #]
Cellformatting Event Handling method
private void Datagridview1_cellformatting (object sender,
Datagridviewcellformattingeventargs e)
{
DataGridView DGV = (DataGridView) sender;
If the cell is a cell of the "Column1" column
if (DGV. Columns[e.columnindex]. Name = = "Column1" && E.value is String)
{
Change cell value to uppercase
String str = e.value.tostring ();
E.value = str. ToUpper ();
Application of the Format,format is complete.
E.formattingapplied = true;
}
}
The Value property of the Datagridviewcellformattingeventargs object of the Cellformatting event starts with the values that are not formatted. When the Value property is set to the text used, the Formattingapplied property is true to inform the DataGridView that the text has been formatted. If you do not do this, DataGridView will reformat the Value property according to the Format,nullvalue,datasourcenullvalue,formatprovider property already set.
? DataGridView the value of the cell input when the user enters
The Datagridview.cellparsing event allows you to set the value entered by the user. The following example: When the English text content is entered, it is immediately changed to uppercase.
[C #]
Cellparsing Event Handling method
private void Datagridview1_cellparsing (object sender,
DataGridViewCellParsingEventArgs e)
{
DataGridView DGV = (DataGridView) sender;
The cell is listed as "column1%2

DataGridView very detailed usage (reproduced)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.