How to Read value from a hidden Column Cell of GridView using Asp.net (C#)
1-First step is to create a Asp.net Project using C#
2-Drag and drop a GridView from the Toolbox on to the Web page and name the GridView to MYGrid.
3-Created The following Columns using BoundField as show below.
4-Make sure the Grid look like this.
5-Create a table with the following variable. Where Id is primary key
6-Add some data to the table
7-Add a label and textbox to the web page
8-Create a connection string for example
String Cn="DataBase_.....";
9- Copy this code to the 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-Add the following to the Web HTMl Page under MyGrid properties
OnRowCreated =" MyGrid _RowCreated" OnRowCommand=" MyGrid_RowCommand"
11-Created the the following method as show below
12-RowCreated Method(This Method is callded to Hide the first cloumn that is Id(Cell 1).
protected void MyGrid_RowCreated(object sender, GridViewRowEventArgs e)
{
e.Row.Cells[1].Visible = false;
}
Note:If User need to use sorting then modify the above MYGrid_RowCreated method as follows.
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 Method
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();
}
}