c # WinForm DataGridView control the development of various operational summary (cell operation, setting the property)

2010-02-24  来源:本站原创  分类:DotNet  人气:873 

c # WinForm DataGridView control the development of various operational summary (cell operation, setting the property)

2010-01-25 20:15

First, the operation of the cell contents

*****// Obtain the current cell contents

Console.WriteLine (DataGridView1.CurrentCell.Value);
/ / Get the current cell's column Index
Console.WriteLine (DataGridView1.CurrentCell.ColumnIndex);
/ / Get the current cell lines Index
Console.WriteLine (DataGridView1.CurrentCell.RowIndex);

******* In addition, the use of DataGridView.CurrentCellAddress property (but not direct access to the cell) to determine where the cell line:

DataGridView.CurrentCellAddress.Y and columns: DataGridView.CurrentCellAddress.X. This is to avoid the cancellation of the share line is very useful to share.
The current cell can be set to change DataGridView object CurrentCell. Can be set by CurrentCell
DataGridView cell activation. Will CurrentCell Make Nothing (null) can deactivate the cell.

/ / Set (0, 0) for the current cell
DataGridView1.CurrentCell = DataGridView1 [0, 0];
Select the mode in the entire line open, you can also set the selected row CurrentCell.
/ / / <summary>
/ / / Down traversal
/ / / </ Summary>
/ / / <param> </ Param>
/ / / <param> </ Param>
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];
)

/ / / <summary>
/ / / Traverse up
/ / / </ Summary>
/ / / <param> </ Param>
/ / / <param> </ Param>
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: this.dataGridView index of the parameters are: columnIndex, rowIndex or columnName, rowIndex
This is different habits.

******** DataGridView set cell read-only:

1) Use ReadOnly property
? If you want, DataGridView cells are not all editors, as long as:
/ / Set read-only DataGridView1
DataGridView1.ReadOnly = true; At this point, the user's new line of operation and remove the line operation has also been blocked.

****** If you want, DataGridView can not edit within a cell, so long as:

/ / Set the first two DataGridView1 whole column of cells read-only
DataGridView1.Columns [1]. ReadOnly = true;
/ / Set DataGridView1 3 of the cell line to read the entire line
DataGridView1.Rows [2]. ReadOnly = true;
/ / Set DataGridView1 of [0,0] cells as read-only
DataGridView1 [0, 0]. ReadOnly = true;

******* DataGridView row header column header cells

/ / Change the first column of the column headers DataGridView1 content
DataGridView1.Columns [0]. HeaderCell.Value = "first column";
/ / Change the contents of DataGridView1 head first trekking
DataGridView1.Rows [0]. HeaderCell.Value = "first line";
/ / Change the top left header cell content DataGridView1
DataGridView1.TopLeftHeaderCell.Value = "left";
In addition you can also change the HeaderText to their content.

/ / Change the first column of the column headers DataGridView1 content
DataGridView1.Columns [0]. HeaderText = "First Column";

*********** DataGridView ToolTip cell settings

DataGridView.ShowCellToolTips = True case, the cell's ToolTip can be expressed. The narrow cell, the cell can not be fully displayed, ToolTip to display the necessary information.
1) Set the contents of the cell ToolTip
/ / Set the contents of the cell ToolTip
DataGridView1 [0, 0]. ToolTipText = "The contents of the cell can not modify";
/ / Set the column header cell ToolTip content
DataGridView1.Columns [0]. ToolTipText = "This column can only enter a number";
/ / Set the row header cell ToolTip content
DataGridView1.Rows [0]. HeaderCell.ToolTipText = "The contents of the cell line can not be changed";
2) CellToolTipTextNeeded event in the cell's ToolTip volume set when a specified then set a relatively low efficiency, which can be used when CellToolTipTextNeeded event. When changes in the cell when ToolTipText will trigger the event. However, when the DataGridView's DataSource is specified and VirualMode = True when the event is not triggered.
/ / CellToolTipTextNeeded event handling
private void DataGridView1_CellToolTipTextNeeded (object sender,
DataGridViewCellToolTipTextNeededEventArgs e)
(
e.ToolTipText = e.ColumnIndex.ToString () + "," + e.RowIndex.ToString ();
)

******* DataGridView cell border, grid line style settings

1) DataGridView to set the border line style
DataGridView border line style is set by DataGridView.BorderStyle property. BorderStyle property setting is a
BorderStyle enumeration: FixedSingle (single, default), Fixed3D, None.
2) cell border line style set cell border line style is set by DataGridView.CellBorderStyle property. CellBorderStyle property settings are
DataGridViewCellBorderStyle enumeration. (Details see MSDN)
In addition, through DataGridView.ColumnHeadersBorderStyle and RowHeadersBorderStyle properties can modify the head DataGridView cell border line style. Property settings are DataGridViewHeaderBorderStyle enumeration. (Details see MSDN)
3) cell border color of the set cell border line color can be set by DataGridView.GridColor property. The default is ControlDarkDark. But only in the CellBorderStyle is set to Single, SingleHorizontal, SingleVertical conditions can change the color of its border lines. Similarly, ColumnHeadersBorderStyle and RowHeadersBorderStyle only be set to Single when to change color.
4) around the cell and down the border line style of a separate set
CellBorderStyle can only be set all the border line of the cell pattern. To separate one side of the border to change the cell style, then, need to use DataGridView.AdvancedCellBorderStyle property. As an example:
'Cells on top and left of the line set to double line
'And right below the cell line set to Single Line
DataGridView1.AdvancedCellBorderStyle.Top = _
DataGridViewAdvancedCellBorderStyle.InsetDouble
DataGridView1.AdvancedCellBorderStyle.Right = _
DataGridViewAdvancedCellBorderStyle.Inset
DataGridView1.AdvancedCellBorderStyle.Bottom = _
DataGridViewAdvancedCellBorderStyle.Inset
DataGridView1.AdvancedCellBorderStyle.Left = _
DataGridViewAdvancedCellBorderStyle.InsetDouble
Similarly, setting the first line of the properties of the cell is: AdvancedRowHeadersBorderStyle, set out in the first cell properties are: AdvancedColumnHeadersBorderStyle.

******* DataGridView cell value custom said

By CellFormatting event, you can customize the value of the cell, said. (Example: Error value when the cell is set to red)
The following example: the "Colmn1" column value to upper case.

/ / CellFormatting event handling
private void DataGridView1_CellFormatting (object sender,
DataGridViewCellFormattingEventArgs e)
(
DataGridView dgv = (DataGridView) sender;

/ / If the cell is "Column1" column of cells
if (dgv.Columns [e.ColumnIndex]. Name == "Column1" & & e.Value is string)
(
/ / The cell value to uppercase
string str = e.Value.ToString ();
e.Value = str.ToUpper ();
/ / Apply the Format, Format completed.
e.FormattingApplied = true;
)
)
CellFormatting event DataGridViewCellFormattingEventArgs Value property of the object is not formatted with a start value of preservation. When the Value property is set, after that the text used to FormattingApplied property as True, this text has been formatted DataGridView completed. If you do not do so, DataGridView has been set according to Format, NullValue, DataSourceNullValue, FormatProvider Property Value property will be re-formatted again.

******* DataGridView the user input, setting the cell input

Events can be set by DataGridView.CellParsing value entered by the user. The following example: When the input when the English text was immediately changed to uppercase.

/ / CellParsing event handling
private void DataGridView1_CellParsing (object sender,
DataGridViewCellParsingEventArgs e)
(
DataGridView dgv = (DataGridView) sender;

/ / Cell as "Column1" when
if (dgv.Columns [e.ColumnIndex]. Name == "Column1" & &
e.DesiredType == typeof (string))
(
/ / Will set the value to uppercase cell
e.Value = e.Value.ToString (). ToUpper ();
/ / End parsing
e.ParsingApplied = true;
)
)

2, row / column operations

******* DataGridView does not show new bottom line:

Usually the bottom line is that users DataGridView new additional line (line head shown *). If you do not want to let the user do not want to show the new additional line that the new line, you can DataGridView object AllowUserToAddRows property to False.
/ / Set the user can not manually add a new row to the DataGridView1
DataGridView1.AllowUserToAddRows = false;
However, you can program: DataGridViewRowCollection.Add additional new lines for the DataGridView.

Fill: bind if the DataGridView's DataSource is the DataView, you can also set DataView.AllowAdd
Property to False to achieve the same effect.

******** DataGridView judge added the line:

DataGridView's AllowUserToAddRows property is True, also allow users to append a new line of occasions, DataGridView is the last line of the new additional line (* line). Use DataGridViewRow.IsNewRow property can determine which line is a new additional line. In addition, through DataGridView.NewRowIndex the line can get a new serial number. In the absence of a new line when, NewRowIndex = -1.
If (DataGridView1.CurrentRow.IsNewRow)

Console.WriteLine ("Append the current behavior of the new line.");
Else
Console.WriteLine ("Append the current line is not a new line.");

******* DataGridView row deletion of users of self-definition:

1) unconditional limit line removal.
By default, DataGridView is to allow users to delete row operations. If you set the DataGridView object AllowUserToDeleteRows property False, the user's line of deletion was banned.
/ / Delete operations against DataGridView1 line.
DataGridView1.AllowUserToDeleteRows = false;
However, by DataGridViewRowCollection.Remove line or can be removed.
Complement: binding a DataView if the DataGridView, then you can control the line through DataView.AllowDelete delete.

******** Line deletion of the conditional processing.

When users delete rows, will cause DataGridView.UserDeletingRow event. In this event, you can determine the conditions and cancel the delete operation.
/ / DataGridView1 of UserDeletingRow events
private void DataGridView1_UserDeletingRow (
object sender, DataGridViewRowCancelEventArgs e)
(
/ / Delete user confirmation before.
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, then cancel.
e.Cancel = true;
)
)

******** DataGridView rows, columns, hidden and deleted:

1) rows and columns hidden
/ / DataGridView1 hide the first column
DataGridView1.Columns [0]. Visible = false;
/ / DataGridView1 hide the first line of
DataGridView1.Rows [0]. Visible = false;
2) the first row, first column hidden
/ / Hide the column headers
DataGridView1.ColumnHeadersVisible = false;
/ / Hide row header
DataGridView1.RowHeadersVisible = false;
3) the deletion of rows and columns
'Remove named "Column1" column
DataGridView1.Columns.Remove ("Column1");
'Remove the first column
DataGridView1.Columns.RemoveAt (0);
'Remove the first row
DataGridView1.Rows.RemoveAt (0);
4) to delete the selected row
foreach (DataGridViewRow r in DataGridView1.SelectedRows)
(
if (! r.IsNewRow)
(
DataGridView1.Rows.Remove (r);
)
)

********* DataGridView column or row against Resize:

1) to prohibit all the columns or rows Resize
/ / Prevent users DataGridView1 change column width of all columns
DataGridView1.AllowUserToResizeColumns = false;

/ / Prevent users from changing the line DataGridView1 の all high
DataGridView1.AllowUserToResizeRows = false;
However, properties can be set by DataGridViewColumn.Width or DataGridViewRow.Height column width and row height.

******* 2) prohibit the designated row or column Resize

/ / Prevent users from changing the first column DataGridView1 column width
DataGridView1.Columns [0]. Resizable = DataGridViewTriState.False;
/ / Prevent users from changing the DataGridView1 the first column of the line width
DataGridView1.Rows [0]. Resizable = DataGridViewTriState.False;
About NoSet
When set to DataGridViewTriState.NotSet Resizable property when actually default to the AllowUserToResizeColumns and AllowUserToResizeRows DataGridView property values set. For example: DataGridView.AllowUserToResizeColumns = False and Resizable is NoSet settings, Resizable = False.
Determine whether it is inherited Resizable set DataGridView's AllowUserToResizeColumns and AllowUserToResizeRows property value, to judge according to State property. If the State property contains ResizableSet, then the note does not inherit settings.
3) column width and row height of the minimum set
/ / The first column of the minimum column width set to 100
DataGridView1.Columns [0]. MinimumWidth = 100;
/ / The first line of the minimum row height is set to 50
DataGridView1.Rows [0]. MinimumHeight = 50;
4) prohibit the user to change the line width of the head and the height of the column headers
/ / Prevent users from changing the height of the column headers
DataGridView1.ColumnHeadersHeightSizeMode =
DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
/ / Prevent users to change the line width of the head
DataGridView1.RowHeadersWidthSizeMode =
DataGridViewRowHeadersWidthSizeMode.EnableResizing;

******* DataGridView column width and row height automatically adjust the settings:

/ / Set all cells, including Header and automatically adjust the column width
DataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
/ / Set including Header and all the cell lines automatically adjust high
DataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
AutoSizeColumnsMode property settings, please refer to msdn the DataGridViewAutoSizeRowsMode enumeration description.
2) automatically adjusts the specified column or row
/ / Adjust first column
DataGridView1.Columns [0]. AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
AutoSizeMode set NotSet, the default is DataGridView.AutoSizeColumnsMode property inheritance.
3) set out in the first line of head height and width adjust

/ / Set the column width of the head can be adjusted
DataGridView1.ColumnHeadersHeightSizeMode =
DataGridViewColumnHeadersHeightSizeMode.AutoSize;
/ / Set the line width of the head can be adjusted
DataGridView1.RowHeadersWidthSizeMode =
DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders;
4) automatically adjust the time
a, temporary, to automatically adjust the column width, and designated it as AutoSizeColumnsMode property.

/ / Let all DataGridView1 automatically adjust the column width.
DataGridView1.AutoResizeColumns (DataGridViewAutoSizeColumnsMode.AllCells);
/ / Make the first column DataGridView1 automatically adjust the column width.
DataGridView1.AutoResizeColumn (0, DataGridViewAutoSizeColumnMode.AllCells); above call to AutoResizeColumns and AutoResizeColumn is DataGridViewAutoSizeColumnMode.AllCells when the specified time parameters can be omitted. Namely:
DataGridView1.AutoResizeColumn (0) and DataGridView1.AutoResizeColumns ()
b, temporary, to automatically adjust the row height
/ / Let all DataGridView1 automatically adjust the row height.
DataGridView1.AutoResizeRows (DataGridViewAutoSizeRowsMode.AllCells);
/ / Make the first line DataGridView1 automatically adjust the row height.
DataGridView1.AutoResizeRow (0, DataGridViewAutoSizeRowMode.AllCells); above call to AutoResizeRows and AutoResizeRow is DataGridViewAutoSizeRowMode.AllCells when the specified time parameters can be omitted. Namely: DataGridView1.AutoResizeRow (0) and DataGridView1.AutoResizeRows ()
c, temporary, so that the first row and column headers automatically adjust
/ / Automatically adjust the height of the column headers
DataGridView1.AutoResizeColumnHeadersHeight ();
/ / Row header width automatically adjusts
DataGridView1.AutoResizeRowHeadersWidth (
DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders);
About the performance:
By AutoSizeColumnsMode or AutoSizeRowsMode attribute The cell automatically adjust the time, so if the adjustment Cishuoguoyu Duo will likely lead to Xingneng decline, especially the number of rows and Lie more and more cases. At this time instead of using DisplayedCells AllCells reduce non-see adjustment of the cell, thereby enhancing performance.

****** DataGridView freeze column or row

1) freeze out
DataGridViewColumn.Frozen property to True, the column on the left of all the columns are fixed, fixed column horizontal scrolling with the scroll bar does not scroll and move around. This important series Fixed display very useful.

/ / DataGridView1 to the left of two fixed
DataGridView1.Columns [1]. Frozen = true;
However, DataGridView.AllowUserToOrderColumns = True, the fixed columns can not be moved to non-fixed columns, and vice versa.
2) line freeze
DataGridViewRow.Frozen property to True, the line above all the lines are fixed, fixed-line when the vertical scroll does not scroll with the scroll bar up and down movement.

/ / DataGridView1 the last 3 lines fixed
DataGridView1.Rows [2]. Frozen = true;

****** DataGridView column order of the adjustment

Set the DataGridView's AllowUserToOrderColumns to True when the user free to adjust the order of the columns.
When the user change the order of the columns when the Index will not change its own, but DisplayIndex changed. You can also change the DisplayIndex procedure to change the order of the columns. When the column order changes lead to ColumnDisplayIndexChanged event:

/ / DataGridView1 of ColumnDisplayIndexChanged event handling
private void DataGridView1_ColumnDisplayIndexChanged (object sender,
DataGridViewColumnEventArgs e)
(
Console.WriteLine ("(0) location changed to (1)"
e.Column.Name, e.Column.DisplayIndex);
)

******** DataGridView add new row to set the default value

Need to specify the default value of the new added row when the event in processing in DataGridView.DefaultValuesNeeded. In addition to handling the incident other than the default setting, you can also specify certain cell ReadOnly attributes.
/ / DefaultValuesNeeded event handling
private void DataGridView1_DefaultValuesNeeded (object sender,
DataGridViewRowEventArgs e)
(
/ / Set the default value of the cell
e.Row.Cells ["Column1"]. Value = 0;
e.Row.Cells ["Column2"]. Value = "-";
)

Third, the global properties of the set for datagridview

******* Use EditMode property

DataGridView.EditMode property is set to DataGridViewEditMode.EditProgrammatically, the user can not manually edit the contents of the cell. However, by program, call DataGridView.BeginEdit ways in which the cell into edit mode for editing.
DataGridView1.EditMode = DataGridViewEditMode.EditProgrammatically;

******* According to the conditions set cell status can not be edited

When a cell coordinates the adoption of a set ReadOnly attribute of the method of the cell too much trouble, you can CellBeginEdit event to cancel cell editing.

*******// CellBeginEdit event handling methods

private void DataGridView1_CellBeginEdit (object sender,
DataGridViewCellCancelEventArgs e)
(
DataGridView dgv = (DataGridView) sender;
/ / If the conditions can be edited check
if (dgv.Columns [e.ColumnIndex]. Name == "Column1" & &
! (Bool) dgv ["Column2", e.RowIndex]. Value)
(
/ / Cancel edit
e.Cancel = true;
)
)

******** DataGridView clipboard operations

DataGridView.ClipboardCopyMode property is set to DataGridViewClipboardCopyMode.Disable situation outside, "Ctrl + C", when pressed, the selected cells will be copied to the system clipboard contents inside. Formats are: Text, UnicodeText, Html, CommaSeparatedValue. Can be directly pasted into Excel,.

ClipboardCopyMode can also set whether the copy Header section: EnableAlwaysIncludeHeaderText copy Header section, EnableWithoutHeaderText not copy. The default is EnableWithAutoHeaderText, Header If you select it, on the copy.
1) the realization of the clipboard to copy programming
Clipboard.SetDataObject (DataGridView1.GetClipboardContent ())
2) DataGridView data clipboard copy paste is easier to achieve, but the direct DataGridView paste to achieve relatively difficult. "Ctrl + V" to paste the press when, DataGridView does not provide, it can only achieve their own.
The following is a simple case when pasting code, copy paste the data to select the beginning cell within the region.

/ / Current cell is selected to judge
if (DataGridView1.CurrentCell == null)
return;
int insertRowIndex = DataGridView1.CurrentCell.RowIndex;
/ / Get the clipboard contents, and press OK division
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 the column headers
if (isHeader)
(
isHeader = false;
continue;
)
/ / Split the data according to Tab
string [] vals = line.Split ('');
/ / Determine whether the uniform number of columns
if (vals.Length - 1! = DataGridView1.ColumnCount)
throw new ApplicationException ("Paste the number of columns is incorrect.");
DataGridViewRow row = DataGridView1.Rows [insertRowIndex];
/ / Line head set
row.HeaderCell.Value = vals [0];
/ / Set cell content
for (int i = 0; i <row.Cells.Count; i + +)
(
row.Cells [i]. Value = vals [i + 1];
)

/ / DataGridView row index +1
insertRowIndex + +;
)

******* DataGridView context menu (ContextMenuStrip)

DataGridView, DataGridViewColumn, DataGridViewRow, DataGridViewCell a ContextMenuStrip property. Can be set to control the DataGridView ContextMenuStrip object context menu is displayed. DataGridViewColumn the ContextMenuStrip property is set apart from the first column of cells other than the right-click menu. DataGridViewRow the ContextMenuStrip property is set apart from the first row of cells other than the right-click menu. DataGridViewCell the ContextMenuStrip property is set to the specified cell right-click menu.

/ / DataGridView's ContextMenuStrip set
DataGridView1.ContextMenuStrip = this.ContextMenuStrip1;
/ / Column set ContextMenuStrip
DataGridView1.Columns [0]. ContextMenuStrip = this.ContextMenuStrip2;
/ / Set the column header ContextMenuStrip
DataGridView1.Columns [0]. HeaderCell.ContextMenuStrip = this.ContextMenuStrip2;
/ / Line set ContextMenuStrip
DataGridView1.Rows [0]. ContextMenuStrip = this.ContextMenuStrip3;
/ / Set the cell ContextMenuStrip
DataGridView1 [0, 0]. ContextMenuStrip = this.ContextMenuStrip4;
The cells on the right menu to set a priority order is: Cell> Row> Column> DataGridView

***** CellContextMenuStripNeeded, RowContextMenuStripNeeded events

CellContextMenuStripNeeded events can be set using the cell right click menu, in particular, but need to right click the cell value changes according to change of time. Than the use of looping through, use the event to set the right menu efficient. However, using the DataSource DataGridView binding but VirtualMode time, the event will not be triggered.
/ / CellContextMenuStripNeeded event handling
private void DataGridView1_CellContextMenuStripNeeded (object sender,
DataGridViewCellContextMenuStripNeededEventArgs e)
(
DataGridView dgv = (DataGridView) sender;
if (e.RowIndex <0)
(
/ / Set the column header ContextMenuStrip
e.ContextMenuStrip = this.ContextMenuStrip1;
)
else if (e.ColumnIndex <0)
(
/ / Row header set ContextMenuStrip
e.ContextMenuStrip = this.ContextMenuStrip2;
)
else if (dgv [e.ColumnIndex, e.RowIndex]. Value is int)
(
/ / If the cell value is integer
e.ContextMenuStrip = this.ContextMenuStrip3;
)
)
Similarly, events can be set by RowContextMenuStripNeeded line right-click menu.

/ / RowContextMenuStripNeeded event handling
private void DataGridView1_RowContextMenuStripNeeded (object sender,
DataGridViewRowContextMenuStripNeededEventArgs e)
(
DataGridView dgv = (DataGridView) sender;
/ / When "Column1" column is the type Bool and the True, the set its the ContextMenuStrip
object boolVal = dgv ["Column1", e.RowIndex]. Value;
Console.WriteLine (boolVal);
if (boolVal is bool & & (bool) boolVal)
(
e.ContextMenuStrip = this.ContextMenuStrip1;
)
)

CellContextMenuStripNeeded event handler method parameters, "e.ColumnIndex =- 1" said the outfit, "e.RowIndex =- 1" said the column headers. RowContextMenuStripNeeded not exist "e.RowIndex =- 1" of the situation.

Fourth, some description for the trigger event

I think that as long as you can remember commonly used, such as mouse operation, some of the common triggering event click; such _CellParsing () generally occur at the end of editing status.

When used in other investigations can be counted, also acquired a long time more.

相关文章