Copy Code code 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 edit of the DataGridView control, set the DataPropertyName property to the column name of the DataTable, such as: Datapropertyname= "name";
B: Select line action:
Copy Code code 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["DataGridViewTextBoxColumn1"]. Value.tostring ();
MessageBox.Show (name);
}
}
E.columnindex refers to the index of the column you clicked, E.rowindex is the index of the row, and if DataGridView has no data, E. rowindex for -1,cells["dataGridViewTextBoxColumn1" refers to the name listed in the DataGridView, can also be expressed in the index, written in Cells[0], that is, the 1th column.
In the GridView of the Web page, add commandargument= "<%# (gridviewrow) Container" to the label where the GridView is going to get the value. RowIndex%> ", and specifies CommandName, the FindControl of the GridView to find the control and get the value of the control.
The code is as follows:
ASP page:
Copy Code code as follows:
<asp:linkbutton id= "Lkselect" runat= "Server" Commandname= "Select" commandargument= "<%# ((GridViewRow) Container). RowIndex%> "> View screenshot </asp:LinkButton>
Background:
Write the following code in the Rowcommand event of the GridView:
Copy Code code 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]; Get a line of GridViewRow
Label Label1 = (label) row. FindControl ("Label1");
String name = Label1. Text;
Response.Write (name);
}
}