asp.net中隐藏GridView的某一列

Python013

asp.net中隐藏GridView的某一列,第1张

获取 GridView 中隐藏列的值

在 GridView 中,我们时常会把作为ID的列隐藏起来,如果在列编辑中将该列的 Visible 值设为 false,是可以实现隐藏该列了,但是却取不到隐藏列的值了。

我们可以在 GridView 的 RowCreated 事件中写入以下代码:

void GridView1_RowCreated(object sender, GridViewRowEventArgs e)

{

e.Row.Cells[0].Visible = false

}

可以实现隐藏第0列,同时也可以用 GridView3.Rows[i].Cells[0].Text 来获取该列的值,但这样做后, GridView 又不能分页了。

经过反复试验,找到了一个好的解决方法:

在 GridView 的 DataKeyNames 属性中,设置主键字段名称数组,可以多个字段,多个字段用逗号隔开。

如: GridView1.DataKeyNames="UserID,UserName"

用以下代码取值:

string UserID = GridViews1.DataKeys[i]["UserID"].ToString()

其中 i 为 GridView 中的 Rows 索引。从0开始到 GridView.Rows.Count-1 结束

如果关键字如有一个字段:GridView1.DataKeyNames="UserID“

可以简化为这样取值:GridView1.DataKeys[i].Value.ToString()

下面给出一个遍历 GridView 的例子:

for ( int i=0 i<GridView3.Rows.Count i++)

{

string UserID = GridViews1.DataKeys[i]["UserID"].ToString()

}

两种办法——

1.style中有display:none为隐藏;block为显示(建议用JS脚本控制)

2.vislble属性:false为隐藏;true为显示(可以在后台类代码中控制)

用不着绑定ID的

你可以给gdv设主键DataKeyNames属性

gdv1.DataSource = ds.Tables[0]

gdv1.DataKeyNames = new string[] { "id" }

gdv1.DataBind()

取的时候可以

string id = gdv1.DataKeys[行号].Value.ToString()