我有一个gridview,它从存储过程中提取数据。在列标题中,我使用了Linkbutton。我想抓住Ctl ID并在点击它时将其存储在变量中。我不确定发生了什么,但我得到了一些细节。以下是我的代码,这与我以前的帖子类似。
ASP.NET
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:LinkButton ID="lnkID" runat="server" OnClick="lblClick1"
Text='<%#Eval("ID") %>'>
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
C#:
GridViewRow row = gv2.SelectedRow;
string controlId = ((LinkButton)row.FindControl("lnkID")).ID;
lblshow.Text = controlId;
有人可以帮助我起床和跑步吗?感谢。
答案 0 :(得分:2)
您可以使用隐藏字段来存储ID:
<ItemTemplate>
<asp:HiddenField
runat="server"
ID="ID"
Value='<%# Eval("ID") %>'
/>
<asp:LinkButton
runat="server"
OnClick="LabelClick"
Text="click me"
/>
</ItemTemplate>
然后:
protected void LabelClick(object sender, EventArgs e)
{
var hiddenField = (HiddenField)((Control)sender).FindControl("ID");
var id = hiddenField.Value;
// Do something with the id
}
更新:
完整的工作示例:
<%@ Page Language="C#" %>
<script type="text/c#" runat="server">
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
grid.DataSource = Enumerable.Range(1, 10).Select(x => new
{
ID = x
});
grid.DataBind();
}
}
protected void LabelClick(object sender, EventArgs e)
{
var hiddenField = (HiddenField)((Control)sender).FindControl("ID");
result.Text = string.Format("selected id: {0}", hiddenField.Value);
}
</script>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form id="Form1" runat="server">
<asp:GridView ID="grid" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:HiddenField
runat="server"
ID="ID"
Value='<%#Eval("ID") %>'
/>
<asp:LinkButton
runat="server"
OnClick="LabelClick"
Text="click me"
/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Label ID="result" runat="server" />
</form>
</body>
</html>
答案 1 :(得分:0)
在OnClick方法lblClick1中,您可以使用:
public void lblClick1(object sender, CommandEventArgs e)
{
int controlId = Convert.ToInt32(e.CommandArgument); //get ID and store it in controlId
lblshow.Text = controlId;
}