Home > front end >  How to get the column name from datagrid vb.net
How to get the column name from datagrid vb.net

Time:03-11

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 enter image description here

And our button click code for the button below the grid to get the column names, would be this:

Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

    For Each o As DataGridColumn In DataGrid1.Columns
        Debug.Print(o.HeaderText)
    Next

End Sub

output:

Fighter
Engine
Thrust
Description
Introduced
View

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:

                    <asp:TemplateColumn HeaderText="row click">
                        <ItemTemplate>
                        <asp:Button ID="cmdRowClick" runat="server" CssClass="btn"
                           OnClick="cmdRowClick_Click" />
                        </ItemTemplate>
                    </asp:TemplateColumn>

So, now the grid looks like this:

enter image description here

And our button click for the row click? This works:

Protected Sub cmdRowClick_Click(sender As Object, e As EventArgs)

    Dim btn As Button = sender
    Dim gRow As DataGridItem = btn.NamingContainer

    Debug.Print("Grid row (index) click = " & gRow.ItemIndex)
    Debug.Print("Database PK row id = " & DataGrid1.DataKeys(gRow.ItemIndex))
    Debug.Print("Fighter Name = " & gRow.Cells(0).Text)

End Sub

Output:

Grid row (index) click = 3
Database PK row id = 4
Fighter Name = Lockheed Martin F-35 Lightning II

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.

  • Related