Copy codeThe Code is as follows:
DataTable DT = new DataTable ();
DT. Columns. Add ("Name ");
DT. Columns. Add ("Sex ");
DataRow dr = DT. NewRow ();
Dr [0] = "Kenny ";
Dr [1] = "male ";
DT. Rows. Add (dr );
A: In the column editing of the DataGridView control, set the DataPropertyName attribute to the column Name of the DataTable, for example, DataPropertyName = "Name ";
B: select a row:
Copy codeThe Code is as follows:
Private void dataGridView_CellContentClick (object sender, DataGridViewCellEventArgs e)
{
If (e. ColumnIndex = 0 & e. RowIndex! =-1 &&! DataGridView. Rows [e. RowIndex]. IsNewRow)
{
String name = dataGridView. Rows [e. RowIndex]. Cells ["maid"]. Value. ToString ();
MessageBox. Show (name );
}
}
E. columnIndex refers to the index of the column you click, e. rowIndex is a row index. If the dataGridView dview has no data, then e. rowIndex is-1. Cells ["dataGridViewTextBoxColumn1"] indicates the name given to the column in The dataGridView. It can also be represented by indexes and written as Cells [0], that is, 1st columns.
If it is in the GridView on the web page, you need to add CommandArgument = "<% # (GridViewRow) Container to the label of the GridView to get the value ). rowIndex %> ", specify CommandName, and use FindControl of the GridView to find the control and obtain the control value.
The Code is as follows:
Asp page:
Copy codeThe Code is as follows:
<Asp: LinkButton ID = "lkSelect" runat = "server" CommandName = "Select" CommandArgument = "<% # (GridViewRow) Container ). rowIndex %> "> View </asp: LinkButton>
Background:
Write the following code in the RowCommand event of the GridView:
Copy codeThe Code is as follows:
Protected void GridView_RowCommand (object sender, GridViewCommandEventArgs e)
{
If (e. CommandName = "Select ")
{
Int index = Convert. ToInt32 (e. CommandArgument); // row index
GridViewRow row = this. GridView. Rows [index]; // obtain a row of GridViewRow
Label label1 = (Label) row. FindControl ("label1 ");
String name = label1.Text;
Response. Write (name );
}
}