Hide a column in GridView and still access its value

In ASP.NET, you can hide a column in a GridView control while still accessing its value programmatically. You can achieve this by setting the column's visibility to false, which will hide it from the user interface but still allow you to access its data in the code-behind. Below is an example demonstrating how to achieve this:

First, let's create a simple GridView in your .aspx page:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowDataBound="GridView1_RowDataBound" >
    <Columns>
        <asp:BoundField DataField="ID" HeaderText="ID" Visible="false" />
        <asp:BoundField DataField="Name" HeaderText="Name" />
        <asp:BoundField DataField="Age" HeaderText="Age" />
    </Columns>
</asp:GridView>

Next, in your code-behind (.aspx.cs or .aspx.vb file), you would bind data to the GridView and access the hidden column's value:

using System;
using System.Data;
using System.Web.UI.WebControls;

public partial class YourPage : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            // Sample data
            DataTable dt = new DataTable();
            dt.Columns.AddRange(new DataColumn[3] { new DataColumn("ID"), new DataColumn("Name"), new DataColumn("Age") });
            dt.Rows.Add(1, "John", 25);
            dt.Rows.Add(2, "Alice", 30);
            dt.Rows.Add(3, "Bob", 35);

            // Bind data to GridView
            GridView1.DataSource = dt;
            GridView1.DataBind();
        }
    }

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            // Accessing hidden column's value
            string hiddenColumnValue = DataBinder.Eval(e.Row.DataItem, "ID").ToString();

            // Do something with the hidden column value
            // For demonstration, let's just print it to the console
            Console.WriteLine("Hidden Column Value: " + hiddenColumnValue);
        }
    }
}

In this example, the "ID" column is hidden using Visible="false" in the GridView's markup. However, in the GridView1_RowDataBound event handler, we can still access the value of the "ID" column using DataBinder.Eval method and the column name.

 
About Us | Terms of Use | Privacy Policy | Disclaimer | Contact Us Copyright © 2012-2024 CodingFusion
50+ C# Programs for beginners to practice