陈斌彬的技术博客

Stay foolish,stay hungry

GridView 隐藏列问题

说明

GridView 是ASP.NET 2.0的新增控件之一,它的出现代替了原有的DataGrid控件.如果你使用过ASP.NET 2.0. 在设计GridView控件时你拖拽了一个Bound Field,那你可能会遇到一个问题.在早期的.NET版本中,如果想要访问一列,但令它不可见,你可以将他的Visible属性设置为false.

但是这在ASP.NET 2.0时无效的.当一个列的可见性设置为false,控件不会再将数据绑定到该列中,所以你尝试得到隐藏列的值时,只能得到一个空的字符串.

However, this does not work in ASP.Net 2.0. When a column’s visibility is set to False, then the Grid does not bind data to the column, and thus when you try to retrieve data from the hidden column, it either blows up or returns an empty string.

对于开发人员来说这个正是可大麻烦,现在提供一个解决方法,希望对你您会有帮助

条件

必须拥有Visual Studio 2005 或者 Visual Web Developer Express并对ASP.NET 2.0有一定了解

解决方案

在RowCreated事件中书写如下代码

void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
    e.Row.Cells[0].Visible = true;  //如果想使第1列不可见,则将它的可见性设为false
   //可以根据需要设置更多的列
}

因为在RowCreated事件(隐藏)在绑定时候发生,所以这样就即能将数据绑定到列上,又隐藏了该列.所 以可以访问到隐藏列的值

下面介绍另外一个可以将数据绑定到GridView控件的方法

Public  void myTestFunction()
{
      string conString="....";//省略
        string sqlquery="...";//省略
       SqlConnection con = new SqlConnection(conString);
            SqlDataAdapter da = new SqlDataAdapter(sqlquery, con);
            DataSet ds = new DataSet();
            da.Fill(ds);
            ds.Tables[0].Columns[0].ColumnMapping = MappingType.Hidden;
            GridView1.DataSouce = ds.Tables[0];
            GridView1.DataBind() ;

}