DoubleM

我的工作是:需求分析、用户体验、项目管理、类设计、技术方向选择、解决复杂的技术问题。 这些领域的事情相对比较轻松,所以也经常有闲写写代码,不过多以折磨自己的大脑为目标,兴趣使然。
  新随笔  :: 订阅 订阅  :: 管理

GridView内单击获取记录主键值

Posted on 2011-08-10 14:48  DoubleMM  阅读(992)  评论(1编辑  收藏  举报

在GridView控件中,每行记录内会放置一个铵钮,当用户点击这个铵钮时,获取当笔记录的主键值。可看演示(是一个gif动画,重新播放尝试刷新网页):

实现这个功能,你需要为GridView控件设置DataKeyNames属性和OnRowCreated事件。
View Code:
View Code
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" DataKeyNames="MediaTypeId"
OnRowCreated
="GridView1_RowCreated">
<Columns>
<!--
其它 TemplateField
-->
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:Button ID="Button1" runat="server" Text="选择" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
.aspx.cs代码:
View Code
 protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType != DataControlRowType.DataRow) return;

if (e.Row.FindControl ("Button1") != null)
{
Button CtlButton
= (Button)e.Row.FindControl ("Button1");
CtlButton.Click
+=new EventHandler(CtlButton_Click);
}
}

private void CtlButton_Click(object sender, EventArgs e)
{
Button button
= (Button)sender;
GridViewRow gvr
= (GridViewRow)button.Parent.Parent;
string pk = GridView1.DataKeys[gvr.RowIndex].Value.ToString();

//do something

//InsusJsUtility objJs = new InsusJsUtility(); //http://www.cnblogs.com/insus/articles/1341703.html
//objJs.JsAlert(pk);
}