Link to home
Start Free TrialLog in
Avatar of jvoconnell
jvoconnell

asked on

Get a value from a gridview cell

Experts,

Newbie question:

I cannot get a value from a cell in a gridview. The gridview loads properly. The first column is a template column with a checkbox. I am able to check whether the user selects the checkbox or not. But I am unable to get any vaule from any other cells in that row.

I try to use:   gridview1.SelectedRow.Cells(2).Text    to get the value I want.
I get a NullReference Exception was unhandled by user code error.

The gridview has 6 columns. The first is the checkbox column and the other 5 all have data populated in them.
Avatar of Death259
Death259
Flag of United States of America image

First make sure that you have the gridview selectionmode property set to FullRowSelect. This is what the code should look like in c# (dunno if this part will really help you or not):
dataGridView1.SelectedRows[0].Cells[2].FormattedValue.ToString()

Open in new window

Try this
For iRow As Integer = 0 To GridView1.Rows.Count - 1
    Dim chkBox As New CheckBox()
    chkBox = DirectCast(GridView1.Rows(iRow).FindControl("mycheckbox"), CheckBox)
    If chkBox.Checked Then
        string str = Gridview1.Rows(iRow).Cells(1).ToString()
    End If
Next

Open in new window

put a breakpoint on this line
add this to watch "gridview1.SelectedRow.Cells", browse all properties to understand it

and open immediate window and put

?gridview1.SelectedRow.Cells
?gridview1.SelectedRow.Cells.Count
?gridview1.SelectedRow.Cells(0).Text
?gridview1.SelectedRow.Cells(1).Text
?gridview1.SelectedRow.Cells(2).Text

Avatar of jvoconnell
jvoconnell

ASKER

HainKurt:

I get "Referenced object has a value of 'Nothing' in the intermdiate window
when you add this to watch

gridview1.SelectedRow
or
?gridview1.SelectedRow

you get nothing... means no row is selected...
maybe you should use this

Dim index As Integer = gridview1.EditIndex
Dim row As GridViewRow = gridview1.Rows(index)

then use

row.Cells(2).Text    
Am I making an incorrect assumption that when the checkbox is checked that the row is "selected"?
ASKER CERTIFIED SOLUTION
Avatar of HainKurt
HainKurt
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
also check this

http://groups.google.com/group/microsoft.public.dotnet.framework.aspnet/browse_thread/thread/6e29b371de01b72f?hl=en

to select a row with a check box, actually when you click checkbox you will do a post back to select that row...
just another approach...
This is it!!!!   Thank you for all of the assistance. It is very much appreciated.