How to make columns invisible at runtime in datagrid?

G

Guest

Hi,
I have a requirement, in which i have to customize the datagrid's
appearance. One part of it is to make certain columns in the datagrid visible
true or false based on certain scenarios.
Please help me to do this...
Thanks,
Imaya.
 
G

Grant Merwitz

DataGrid1.Columns[0].Visible = false;

In your code behind, determine if you should show a column, and use the code
above to set the visibility
 
G

Guest

Your best bet is to dynamically build the columns you wish to add. Here is an
example. Suppose, you want the Northwind database (mostly because it ships
with SQL Server and is easy to connect to). You also desire to show customer
records, but for the average Joe, you only show Customer ID and Company Name.

1. Set up a connection to SQL Server in Visual Studio.
2. Drag the Customer table onto an ASPX page (no, I do not normally do this
in real life, but drag and drop is good enough for an example).
3. Drag a DataGrid on the page
4. Create the code

//Adding columns dynamically
//Assumes you have filled the DataSet (aka ds)
BoundColumn bc = new BoundColumn();
bc.HeaderText = "Customer ID";
bc.DataField = "CustomerID";
DataGrid1.Columns.Add(bc);

bc = new BoundColumn();
bc.HeaderText = "Company Name";
bc.DataField = "CompanyName";
DataGrid1.Columns.Add(bc);

//Binding portion
DataGrid1.DataSource = ds.Tables[0].DefaultView;
DataGrid1.DataBind();

NOTE: You can use other column types other than a simple BoundColumn, but
they will require a bit more thought. To determine how the columns are going
to be set up, use the Property Builder for the DataGrid and play around with
how the DataGrid will look for different scenarios. Then, set up routine(s)
that add the column(s) and call the correct routine (or a routine with the
correct parameter(s) to build the grid).

Remember, everything is an object. You can set objects declaratively (let
the engine do the actual work) or programatically. Either way, with Grids,
columns are added to the column colllection to create your rendered DataGrid.

--
Gregory A. Beamer
MVP; MCP: +I, SE, SD, DBA

***************************
Think Outside the Box!
***************************
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top