问题
In Gridview, I want to capture the Column Id's value for the selected row. When I click "Select" and Click "Go" button, I receive this output:
Captured: MainContent_GridView1
How do I select the ID of that particular row?
protected void btnGo_Click(object sender, EventArgs e)
{
try
{
GridViewRow row = GridView1.SelectedRow;
String RowID = row.ClientID;
Response.Write("Captured: " + RowID);
}
catch (Exception ex)
{
Response.Write("Error:"+ ex.ToString());
}
}
回答1:
One way to get the field values in a row is to add the field names to the DataKeyNames of the GridView:
<asp:GridView ID="GridView1" runat="server" DataKeyNames="Id,Phone" ... >
In code-behind, you can get the values this way:
int Id = (int)GridView1.DataKeys[row.RowIndex].Values["Id"];
string phone = (string)GridView1.DataKeys[row.RowIndex].Values["Phone"];
I included Phone in the list to show that several fields can be specified. In your case, DataKeyNames would only contain Id.
回答2:
I think this is what you mean, you have a GridView that is showing the id in one of the columns. So, if it was the first column, you could do something like
GridViewRow row = GridView1.SelectedRow;
string id = row.Cells[0].Text;
Is that what you mean?
回答3:
String Id = GridView1.SelectedRow.Cells[0].Text
来源:https://stackoverflow.com/questions/36637237/in-gridview-i-want-to-capture-the-column-ids-value-for-the-selected-row