Categories: MSDN / DotNet / Java / Scripts / Linux / PHP Ask - La ask - La Answer

Dynamically adding/removing columns in datagrid

I create a report by allowing users to select certain criteria from dropdownlistbox.

Dropdowns: site, project, startDate, endDate, reporting level (summary or agent detail)

I have the following datagrid with 7 columns:

<asp:datagrid id="grdResults" runat="server" Height="50px" Font-Names="Tahoma" Width="900px" Font-Size="XX-Small" BorderColor="Silver" ForeColor="Black" PageSize="1" adding="1" AutoGenerateColumns="False" BorderStyle="Solid"
CellSpacing="1" HorizontalAlign="Center">
<Columns>
<asp:BoundColumn DataField="iMsSiteId" HeaderText="Site"></asp:BoundColumn>
<asp:BoundColumn DataField="sProject" HeaderText="Project"></asp:BoundColumn>
<asp:BoundColumn DataField="sCalldate" HeaderText="Calldate"></asp:BoundColumn>
<asp:BoundColumn DataField="sAgentId" HeaderText="Agentid"></asp:BoundColumn>
<asp:BoundColumn DataField="sFirstName" HeaderText="First Name"></asp:BoundColumn>
<asp:BoundColumn DataField="sLastName" HeaderText="Last Name"></asp:BoundColumn>
<asp:BoundColumn DataField="sRevenue" HeaderText="Revenue" DataFormatString="{0:$###,###.##}"></asp:BoundColumn>
</Columns>
</asp:datagrid>

When agent detail is selected from the dropdown the datagrid should contain agentid, firstname, and lastname columns.
When summary is selected those 3 columns shouldn't be visible.

How can I do this dynamically?

Thanks,
Ninel
[1557 byte] By [ninel] at [2007-11-11 8:36:13]
# 1 Re: Dynamically adding/removing columns in datagrid
hii,
u have populated the datagrid or not?
i have the populate code for datagrid

Dim con As New SqlConnection(ConfigurationSettings.AppSettings("Connstring"))
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
con.Open()
If Not Page.IsPostBack Then
getsql = ("select * from student")
Dim cmd As New SqlCommand(getsql, con)
dr = cmd.ExecuteReader
DataGrid2.DataSource = dr
DataGrid2.DataBind()
dr.Close()
End If
End Sub

u need to write the code on dropdown's selection so give the proper condition & use following line of code.
i have written the code on a buttons click event tht wen d textbox is empty at the time of page load the datagrid will b populated normally but when u will
enter the text "aaa" in textbox then the datagrid's second column will b hided

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If TextBox1.Text = "aaa" Then
DataGrid2.Columns(2).Visible = False
Else
DataGrid2.Columns(2).Visible = True
End If
End Sub
rash_2211 at 2007-11-11 23:13:04 >