I have a situation where I have a gridview bound to a SqlDataSource. The SqlDataSource runs a query to use to populate the grid with data. So far, so good. However, I have a column in the gridview that I want to populate with data not included in the
original query. To do so, I need to extract a key value from one of the cells in the gridview and use it to run another query and get the data that I need.
The problem is - I'm not able to access the data in the cells of the row during the RowDataBound event - at least not so far. Below is the code I've tried so far, along with the results:
'tried this
'ID = CType(e.Row.DataItem, DataRow).Item("item_id").ToString()
'that didn't work - DataItem was nothing
'tried this...
'ID = e.Row.Cells(1).Text
'that didn't work - just gave me one of three things, depending upon the row it was on.:
' the column header - item_id
' an empty string
'
Any ideas?
I think you are looking at all the rows of the grid, you should only be looking at the data rows add a condition
like
if(e.Row.RowType == DataControlRowType.DataRow)
then e.Row.Cell(1).Text ///should you give you the cell valueI tried your code above, and that seems to be the condition where e.Row.Cells(1).Text returns an empty string.
ok, when you look at from the front end do you have any data in that cell(1) or for that matter try to change the cell Index and see if you get data for any other cells or not. Hope you are binding the data to the grid properly. If you need more help please
post more code.
check RowType like Anwar's sample code. Dim id as String = DataBinder.Eval(e.Row.DataItem, "id")
Yes, the data is present in cell(1), although cell(1) is set as being a not-visible field.
Aha! There's the issue - if I make the column visible, then the data is there. It's only when the visible property is set to false that the data is blank in that column.
But that's still not an adequate solution, because I don't want that column visible.
Right. Non Visible columns data is not accessible. Remove the visible property and create a css class something like Hidden: display:none; and set the CssClass=Hidden to that cloumn.
I'm totally confused on that one, Anwar. You'll have to flesh that out a bit more for me.
Remove Visible=False property from the column and add the below code
.hidden
{
display: none;
}
Have you try get it directly from database? Dim id as String = DataBinder.Eval(e.Row.DataItem, "id")?
Thanks, Anwar - I didn't know you could apply css to a column like that. I still have much to learn. Thanks for the tip!
沒有留言:
張貼留言