我想在包含按钮控件的gridview中添加一列。我使用ID(整数和主键)作为Gridview的第一列。我想要的是当用户点击gridview的任何给定行上的按钮时,我希望能够确定所单击按钮所属的行的ID
Vam Yip
答案 0 :(得分:4)
在网格视图的模板中,将按钮的CommandArgument属性绑定到行的ID。然后在按钮单击事件上,检查事件args中的commandArgument属性。这将为您提供ID
答案 1 :(得分:1)
与@ Midhat的回答一起,这里有一些示例代码:
代码隐藏:
public partial class _Default : System.Web.UI.Page
{
List<object> TestBindingList;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
TestBindingList = new List<object>();
TestBindingList.Add(new { id = 1, name = "Test Name 1" });
TestBindingList.Add(new { id = 2, name = "Test Name 2" });
TestBindingList.Add(new { id = 3, name = "Test Name 3" });
this.GridView1.DataSource = TestBindingList;
this.GridView1.DataBind();
}
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
int index = Convert.ToInt32(e.CommandArgument);
this.Label1.Text = this.GridView1.DataKeys[index]["id"].ToString();
}
}
}
标记:
<form id="form1" runat="server">
<asp:GridView ID="GridView1" runat="server"
onrowcommand="GridView1_RowCommand" DataKeyNames="id">
<Columns>
<asp:TemplateField HeaderText="ButtonColumn">
<ItemTemplate>
<asp:Button ID="Button1" runat="server" CausesValidation="false"
CommandName="Select" Text="ClickForID"
CommandArgument="<%# ((GridViewRow)Container).RowIndex %>" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Label ID="Label1" runat="server" Text="ID"></asp:Label>
</form>