This code worked beautifully for me. It is pretty much self-explanatory.
How to Hide a DataGrid Column Dynamically?
Author Date Of Submission User Level
Sushila D. Patel 06/01/2003 Intermediate
Introduction:
To hide few columns in the datagrid we can make use of the tag <asp:boundcolumn> assign the relevent values to the attributes DataField,HeaderText and set the visible property to true/false. i.e by giving
<asp:datagrid id="DataGrid1" style="Z-INDEX: 101; LEFT: 18px; POSITION: absolute; TOP: 11px" runat="server"
AutoGenerateColumns="False">
<Columns>
<asp:BoundColumn DataField="CategoryName" HeaderText="CategoryName"></asp:BoundColumn>
<asp:BoundColumn DataField="Description" HeaderText="Description" visible="false"></asp:BoundColumn>
</Columns>
</asp:datagrid>
This technique becomes cumbersome if we need to show all except one field from the database table.So solution is query the datbase without including that field in the SQL statement or use a different way to work around with this.
In this article we'll see how to hide the columns dynamically in the Datagrid. For this snippet we would use the Categories Table from the Northwind Database. We'll hide the column Picture from the Categories Table to be displayed in the Datagrid.
Snippet:
Create a webform with a DataGrid control.
<asp:DataGrid AutoGenerateColumns="False" id="DataGrid1"
style="Z-INDEX: 101; LEFT: 20px; POSITION: absolute; TOP: 12px" runat="server">
</asp:DataGrid>
In the code behind the code is as follows:
Dim myconnection As SqlClient.SqlConnection
Dim myda As SqlClient.SqlDataAdapter
Dim ds As DataSet
myconnection = New SqlClient.SqlConnection("Server=localhost;uid=sa;p assword=;database=northwind;")
myda = New SqlClient.SqlDataAdapter("Select * from Categories", myconnection)
ds = New DataSet()
myda.Fill(ds, "AllTables")
Dim i As Integer
'To navigate through the records
For i = 0 To ds.Tables(0).Columns.Count - 1
Dim objbc As New BoundColumn()
objbc.DataField = ds.Tables(0).Columns(i).ColumnName
objbc.HeaderText = ds.Tables(0).Columns(i).ColumnName
If objbc.DataField = ds.Tables(0).Columns("Picture").ColumnName Then
objbc.Visible = False
End If
DataGrid1.Columns.Add(objbc)
DataGrid1.DataSource = ds.Tables(0)
DataGrid1.DataBind()
Next
http://www.c-sharpcorner.com/Code/20...ridColDyna.asp
Hope this helps.
Richard