DataGridView binding DataTable data and related operation implementation code
- 2020-05-07 19:30:27
- OfStack
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 DataTable, such as DataPropertyName="Name";
B: selected line operation:
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 is the index of the column you clicked on. e.RowIndex is the index of the row. If dataGridView has no data, e.RowIndex is -1.
If you're in GridView on web, you need to put CommandArgument= in the tag where GridView is going to get the value." < %#((GridViewRow)Container).RowIndex % > "And specify CommandName to find the control by FindControl of GridView and get the value of the control.
The code is as follows:
asp page:
<asp:LinkButton ID="lkSelect" runat="server" CommandName="Select" CommandArgument="<%#((GridViewRow)Container).RowIndex %>"> Check the screenshot </asp:LinkButton>
Background:
Write the following code in GridView RowCommand event:
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]; // To obtain GridViewRow the 1 line
Label label1 = (Label)row.FindControl("label1");
String name = label1.Text;
Response.Write(name);
}
}