如何隐藏 GridView 列单元格以及如何检索隐藏单元格的值






2.18/5 (13投票s)
2007年7月6日
1分钟阅读

80962
隐藏和检索 GridView 列的值
如何使用 Asp.net (C#) 读取 GridView 隐藏列单元格中的值
1-第一步是使用 C# 创建一个 Asp.net 项目
2-将 GridView 从工具箱拖放到网页上,并将 GridView 命名为 MYGrid。
3-使用 BoundField 创建以下列,如下所示。
4-确保 Grid 的外观如下所示。
5-创建一个包含以下变量的表。其中 Id 是主键
6-向表中添加一些数据
7-向网页添加一个标签和文本框
8-创建一个连接字符串,例如
String Cn="DataBase_.....";
9- 将此代码复制到 Page_Load
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection(Cn);
SqlDataAdapter ad = new SqlDataAdapter("Select * GData from GData" , Cn);
DataSet ds = new DataSet();
ad.Fill(ds);
MyGrid.DataSource = ds.Tables[0];
MyGrid.DataBind();
}
10-在 MyGrid 属性下,将以下内容添加到 Web HTML 页面
OnRowCreated =" MyGrid _RowCreated" OnRowCommand=" MyGrid_RowCommand"
11-创建以下方法,如下所示
12-RowCreated 方法(此方法被调用以隐藏第一列,即 Id(单元格 1)。
protected void MyGrid_RowCreated(object sender, GridViewRowEventArgs e)
{
e.Row.Cells[1].Visible = false;
}
注意:如果用户需要使用排序,请按如下方式修改上述 MYGrid_RowCreated 方法。
protected void MyGrid_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
e.Row.Cells[1].Visible = false;
}
if(e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[1].Visible = false;
}
}
13-RowCommand 方法
protected void MyGrid_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = MyGrid.Rows[index];
TextBox1.Text = row.Cells[1].Text.ToString();
}
}