0

I'm working with a GridView that I'm populating programmatically. In order to access the ID value, I have to have it as one of the columns (as opposed to a ListBox, where I was able to assign the value to each entry in a hidden way). Is there a way to hide that ID column, but still use the value?

The columns are being auto-generated through the code and I'm accessing the ID value using DataKeys.

4

4 回答 4

2

Assign the ID to the DataKeyNames collection will work fine, is that an issue for you? The data keys is available for each row, not showing up in the UI, but still accessible with the row data, so you can get the ID for each row. You just have to get it from the DataKeys collection, instead of the row directly.

You can add code to hide the first column (the ID) so that it doesn't appear, and rely on using the datakeynames to get the ID value... if that doesn't work, could you elaborate on why so I can adjust my answer..

于 2013-07-19T16:14:35.370 回答
2

Here's a general overview of what you can do. It's not complicated. You databind as usual, but while doing that you find the index of the ID column. Then you use that index to hide the column on the RowCreated event. If you search for how to hide a column using auto-generated columns, you'll run into several answers following the method I'm using for hiding.

Private IDColumnIndex As Integer      //Class scope - we need to use it in multiple methods

Public Sub PageLoad() Handles Me.Load //or wherever your databind is happening
    Dim source As New DataTable()
    IDColumnIndex = source.Columns("id").Ordinal   //Gets column index of "ID" column

    view.DataSource = source
    view.DataBind()
End Sub

//Hide our "ID" auto-generated column.
Public Sub view_RowCreated(ByVal sender As Object, ByVal e As GridViewRowEventArgs) Handles view.RowCreated
    e.Row.Cells(IDColumnIndex).Visible = False
End Sub
于 2013-07-19T16:45:23.017 回答
1

You can get the ID value if you add the ID column to the DataKeyNames property of your GridView. msdn link here

myGrid.DataKeys[myRow.RowIndex].Value.ToString();
于 2013-07-19T16:15:19.500 回答
1

I usually add a visible column But then make the template for the colmn jus a space or something. Then in the ID for the column, I put the ID I want to track. This technique let's me easily find the ID of a row using javascript when the content has been rendered into HTML.

If you let the grid view do its business rendering with the hidden data keys, you may never find the ID in client side browser javascript in all that mess.

于 2013-07-19T17:16:31.000 回答