top button
Flag Notify
Site Registration

How to generate GridView columns dynamically based on user selection?

0 votes
332 views
How to generate GridView columns dynamically based on user selection?
posted Dec 23, 2015 by Sathaybama

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote
 
Best answer

In case we have to give ability to the user to select the columns that should appear in the GridView, we can follow this approach.
Sometimes due to large number of columns to be displayed on the page in the GridView or give a precise look to the data in GridView, we need to show only those columns in the GridView that is selected by the user. In this article we are going to learn how to dynamically generate GridView columns based on user selection.
ASPX Code

<div>

Select column to show in the GridView:
<asp:CheckBoxList runat="server" ID="chkFields" DataTextField="Column_name" DataValueField="Column_name" RepeatDirection="Horizontal" RepeatLayout="Flow" />

<p>

<asp:Button ID="btnSub" runat="server" Text="Show" OnClick="ShowGrid" />
</p>

<asp:GridView ID="GridView1" runat="server" EnableViewState="false" AutoGenerateColumns="false" />
</div>

In the above code snippet, we have a CheckBoxList control that lists all the columns of my database table. Apart from this, we have a Show button and a GridView. After selecting the columns from the CheckBoxList control user click on the Show button and accordingly the GridView columns are displayed on the page. Notice that AutoGenerateColumns property is set to false in the GridView.
enter image description here

Code behind

string _connStr = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;

protected void Page_Load(object sender, EventArgs e)

{

if (!IsPostBack)

{

BindTableColumns();
}
}

private void BindTableColumns()

{

DataTable table = new DataTable();

using (SqlConnection conn = new SqlConnection(_connStr))

{

using (SqlCommand cmd = new SqlCommand("sp_columns", conn))

{

cmd.CommandType = CommandType.StoredProcedure;

cmd.Parameters.AddWithValue("@table_name", "PersonalDetail");

// get the adapter object and attach the command object to it

using (SqlDataAdapter ad = new SqlDataAdapter(cmd))

{

// fire Fill method to fetch the data and fill into DataTable

ad.Fill(table);
}

chkFields.DataSource = table;

chkFields.DataBind();
}
}
}

private void GetData()

{

DataTable table = new DataTable();

// get the connection

using (SqlConnection conn = new SqlConnection(_connStr))

{

// write the sql statement to execute

string sql = "SELECT AutoId, FirstName, LastName, Age, Active FROM PersonalDetail ORDER By AutoId";

// instantiate the command object to fire

using (SqlCommand cmd = new SqlCommand(sql, conn))

{

// get the adapter object and attach the command object to it

using (SqlDataAdapter ad = new SqlDataAdapter(cmd))

{

// fire Fill method to fetch the data and fill into DataTable

ad.Fill(table);
}
}
}

// specify the data source for the GridView

GridView1.DataSource = table;
// bind the data now

GridView1.DataBind();
}



protected void ShowGrid(object sender, EventArgs e)

{

foreach (ListItem item in chkFields.Items)

{

if (item.Selected)

{

BoundField b = new BoundField();

b.DataField = item.Value;

b.HeaderText = item.Value;

GridView1.Columns.Add(b);
}
}

this.GetData();
}

In the above code snippet, we have called BindTableColumns() method that uses sp_columns stored procedure (no need to create it, it comes by default with SQL Server) to retrieve the column names of the database table and populates into the CheckBoxList control (In case you have column names coming from more than one database table, you will need to add them one by one into the CheckBoxList control).

When user click on Show button after selecting the columns from the CheckBoxList control, we are calling ShowGrid server side method. In this method we are iterating through the columns of the GridView and if selected, adding into the GridView column collection. At last we are calling the GetData method that fetches the records from the database and populates into the GridView.

As we have specified AutoGenerateColumns to false so whatever columns will be added to the GridView will only be displayed on the page.

answer Dec 23, 2015 by Shivaranjini
Similar Questions
+2 votes

Example in student mark list table if user change "Status" to Pass or Fail

IF Fail means change the Grid row color to RED

Else Pass means Change to Green Color

...