asp.net中gridview隐藏一列并且使用这列数据的方法

方法一:在RowCreated事件中添加如下代码可隐藏此列,使用this.grdView.Rows[index].Cells[1].Text获取值,index为行号。

1     protected void grdView_RowCreated(object sender, GridViewRowEventArgs e)
2     {
3         if (e.Row.RowType == DataControlRowType.DataRow || e.Row.RowType == DataControlRowType.Header)
4         {
5             e.Row.Cells[1].Visible = false;
6         }
7     }

备注:方法一在无数据绑定时依旧会显示需要隐藏列的表头,不添加e.Row.RowType == DataControlRowType.DataRow || e.Row.RowType == DataControlRowType.Header可能会报错。

 

方法二:使用属性DataKeyNames,在页面控件上把需要隐藏的列加上 Visible="false"

 1 protected void Page_Load(object sender, EventArgs e){
 2     if (!this.IsPostBack){
 3       this.grdView.DataKeyNames = new string[] { "FLD_ID" };
 4     }
 5 }    
 6 
 7 protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e){
 8    int index = Convert.ToInt32(e.CommandArgument); //行索引
 9     string strUser = this.grdView.DataKeys[index]["FLD_ID"].ToString(); }

备注:方法二中添加的DataKeyNames是表格中的数据源字段。我刚开始用的方法一因为有问题,所以更改为方法二了,没有发现什么问题。

posted @ 2020-04-22 15:16  昨天忆  阅读(990)  评论(0编辑  收藏  举报