I have a datagrid on the asp.net page. I need to generate the column name of the datagrid when the user clicking the button. I found it on the web ASP.Net Datagrid Get Column Index from Column Name
but it doesn’t work. The total of the datagrid column is 0. There are many code example for datagridview, but I am using datagrid. Would someone tell me how to do it. Thanks in advance.
There is my code:
For Each c As DataControlField In dgrd.Columns
Dim stringname As String = c.HeaderText
Next
There is the binding on aspx page:
<asp:TemplateColumn HeaderText="Date">
<ItemTemplate>
<%# DataBinder.Eval(Container.DataItem, "Date", "{0:ddMMMyyyy}") %>
</ItemTemplate>
</asp:TemplateColumn>
<asp:BoundColumn DataField="Number" HeaderText="Number" />
2
Answers
It looks like it needs
As DataGridColumn
instead ofAs DataControlField
:If you assign the HeaderText to the same variable each time round the loop, it will end up with only the last value.
Hum, not sure it at all common to generate the column name? Does not one usually setup, or define the column names in the markup and layout for the grid?
We don’t normally "generate" or "create" the column name(s) in code – so that’s a bit confusing here.
Ok, as long as the data grid been loaded up, then you should be fine.
So, as a general rule, you can fill a data grid. Say our code behind is this:
And say the data grid markup is this:
Ok, so now we have/get this:
And our button click code for the button below the grid to get the column names, would be this:
output:
So, you can get the columns, but you have to make sure the grid been filled up with data BEFORE you attempt to use the data grid.
And manybe you want a row click. So, lets add a plane jane asp.net button to the grid, say like this:
So, now the grid looks like this:
And our button click for the row click? This works:
Output:
Note how we can still get the database PK "id" value, but it is NOT displayed anywhere in the grid – we used the datakey setting for this, and it is a great feature, since then we don’t have to expose, or show or hide the PK data base row id, but can still get that PK "id" value in code behind.
So, we could now navigate based on that database "ID" and say pass it on to the next page to display more information about that give thing selected (clicked on) in that row.