如何取得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都有这样的属性。

posted on 2007-03-29 21:17  小姜  阅读(1032)  评论(1编辑  收藏  举报