如何取得GridView被隐藏列的值

情景:

要显示一个摘要数据表,每行有一个Detail按钮,用户点击后要打开一个显示详细信息的页面。

使用GridView显示数据,绑定到一个sqldatasource。我的数据源中包含一列主键,我不想显示它,但是当用户点击Detail按钮后,需要取出这列的值传递给下一个页面。

问题:

在GridView中,在用户点击按钮的事件中可以使用下面的方法取当前行中某一列的值(从帮助里copy出来的代码)

int index = Convert.ToInt32(e.CommandArgument);
// Retrieve the row that contains the button clicked 
// by the user from the Rows collection.
GridViewRow row = CustomersGridView.Rows[index];
            
item.Text = Server.HtmlDecode(row.Cells[2].Text);


问题来了,如果你把一列设为隐藏,就发现取出来的是空值。

 

解决方案:

1 在GridView中将主键EmployeeID这一列设为隐藏Visible ="false" , 增加一个button列。同时要注意,将GridView的DataKeyNames设置为"EmployeeID" 

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"   DataKeyNames="EmployeeID"  DataSourceID="SqlDataSource1" OnRowCommand="GridView1_RowCommand"        >
        <Columns>
            <asp:BoundField DataField="EmployeeID" HeaderText="EmployeeID" ReadOnly="True" SortExpression="EmployeeID"  Visible ="false" />
            <asp:BoundField DataField="Title" HeaderText="Title" SortExpression="Title" />
            <asp:BoundField DataField="LastName" HeaderText="LastName" SortExpression="LastName" />
            <asp:BoundField DataField="FirstName" HeaderText="FirstName" SortExpression="FirstName" />
            <asp:BoundField DataField="WorkPhone" HeaderText="Phone" SortExpression="WorkPhone" />
            <asp:BoundField DataField="MobilePhone" HeaderText="Mobile" SortExpression="MobilePhone" />
            <asp:ButtonField HeaderText = "Detail" ButtonType="Button" Text ="Detail" CommandName="Detail"    />  
        </Columns>
    </asp:GridView>

2 在GridView1_RowCommand事件中取得EmployeeID列的值

   protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Detail")
        {

            // Convert the row index stored in the CommandArgument
            // property to an Integer.
            int index = Convert.ToInt32(e.CommandArgument);

            // Get the Key value from the GridView control.
            DataKey key = GridView1.DataKeys[index ];

            string employeeid = key.Value.ToString() ;

            Session["EmployeeID"] = employeeid;
            Server.Transfer("EditEmployee.aspx");

        }

这里,要点是GridView使用了DataKeys来保存关键列的数据,而不是以前ASP1.1中的那种方式了。如果要把列加入DataKeys,需要在GridView的DataKeyNames属性中加入列名,而且支持多个列,中间用逗号分割。不仅GridView有此特性,DetailView和FormView都有这样的属性。

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值