Link to home
Start Free TrialLog in
Avatar of SaraDob
SaraDob

asked on

Fetching Null Values of GUID ,when selction is made in Grdiview

Hi masters,experts,Gurus....
Please solve this..I have been with problem from past 3 hrs..
I have a gridview, which has LocID, Location,City.I have hidden the  Locid cloumn.
Upon click of a button , the user selects a location.The location will be displayed in textbox, but the LOcid goes to the hidden value.I have made Locid and Location as Datakeys. I'm able to show the value of Locid( as such :eee000317-aa7e-46ca-a329-0fdac6411ead)  in the gridview(if i make it visible="true" for testing purposes),But when i select the location, the hidden value displayes LOCid as 000000-000-0000-0000...
The way i access the id in the code behind is:
 Dim LocId As Guid = CType(Me.GrdLocation.DataKeys(e.NewSelectedIndex)("LocID"), Guid)
        Dim Loc As String = Me.GrdLocation.DataKeys(e.NewSelectedIndex)("Location")
        Label1.Text = Convert.ToString(LocId)
        GrdLocation.Visible = False

HELPPPPPPPPPPPPPPPPPP
Avatar of Juan_Barrera
Juan_Barrera
Flag of New Zealand image

Hi SaraBob,
For some reason, your GUID is wrong (eee000317-aa7e-46ca-a329-0fdac6411ead). It should be 8-4-4-12 characters, not 9-4-4-12
It should work this way (if you have the right GUID):
 Dim LocId As Guid = CType(Me.GrdLocation.DataKeys(e.NewSelectedIndex)("LocID"), Guid)
Label1.Text = LocId.ToString
 For testing purposes, try to declare LocId like this (note the 8-4-4-12 format):
Dim LocId As New Guid("ee000317-aa7e-46ca-a329-0fdac6411ead")
Label1.Text = LocId.ToString
Avatar of SaraDob
SaraDob

ASKER

Hi Juan barrera,

"For some reason, your GUID is wrong (eee000317-aa7e-46ca-a329-0fdac6411ead). It should be 8-4-4-12 characters, not 9-4-4-12"
I checked in the database, the GUID is 8-4-4-4-12.I had made a mistake, when i pasted it here , i suppose.

I did as you said for testing purposes,still my GUID comes as follows:
00000000-0000-0000-0000-000000000000
I have attached a file(.doc), which shows the Event page and code behind.The 00000-0000-0000-000...
Shows the label content.You can see the LocId, which has 8-4-4-4-12.
please have a look at it and help me with this code.

Event.bmp
SOLUTION
Avatar of Juan_Barrera
Juan_Barrera
Flag of New Zealand 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
Avatar of SaraDob

ASKER

Sorry..that was only a bmp file..Not Doc.. I wil test for your solution right now
Avatar of SaraDob

ASKER

This is the error i'm getting ,
System.NullReferenceException: Object reference not set to an instance of an object.
Pointing to to this line:
  Dim s As String = LocId.ToString()

So i you said, the datakeys are fetvhing Null values..
What shoukd be done
Hi SaraBob,

Try by calling GrdLocation.DataBind() before the DataKeys. I guess that, however you are binding the grid, it hasn't been data-bound yet when you try to access the collection.

GrdLocation.DataBind()
Dim LocId As Object = Me.GrdLocation.DataKeys(e.NewSelectedIndex)("LocID")
Dim s as String = LocId.ToString()

Open in new window

Avatar of SaraDob

ASKER

Hey Juan_Barrera:
Thanks for the quick reply.I really appreciated it.As this has to deliverered by EOB, i'm struggling, as your helping me out.I appreciate your patience.

I have pasted the code, whats happening here :
// This code behind is for On click of a button, i make the gridview=true, filling it with datasource
Protected Sub btnLocation_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnLocation.Click
        GrdLocation.Visible = True
        Dim MyCompCommand As SqlDataAdapter = New SqlDataAdapter("Select Locations.LocId,Locations.LocationName As Location,Locations.City,Locations.State,StateProvince.Countryregionname as Country from Locations,Stateprovince where Locations.Stateprovinceid=StateProvince.Stateprovinceid order By LocationName ASC", MyConn)

        Dim DS As DataSet = New DataSet()
        MyCompCommand.Fill(DS, "Locations")

        GrdLocation.DataSource = DS.Tables("Locations").DefaultView
        GrdLocation.DataBind()
        MyConn.Close()
    End Sub
 
// This is the code for Selecting the GUID
    Sub GrdLocation_SelectedIndexChanging(ByVal sender As Object, ByVal e As GridViewSelectEventArgs)

        'Dim LocId As Guid = CType(Me.GrdLocation.DataKeys(e.NewSelectedIndex)("LocID"), Guid)
        'Dim Loc As String = Me.GrdLocation.DataKeys(e.NewSelectedIndex)("Location")
        'Label1.Text = Convert.ToString(LocId)
        GrdLocation.DataBind()
        Dim LocId As Object = Me.GrdLocation.DataKeys(e.NewSelectedIndex)("LocID")
        Dim s As String = LocId.ToString()

        Label1.Text = s.ToString
        GrdLocation.Visible = False
  End Sub

When i did databindbefore the datakeys collection, i got a error loke :System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
pointing to datakeys fetching part
Sara, you should rebind the grid on every postback, don't do it only onButtonClick:

Protected Sub BindGrid()
 
        Dim MyCompCommand As SqlDataAdapter = New SqlDataAdapter("Select Locations.LocId,Locations.LocationName As Location,Locations.City,Locations.State,StateProvince.Countryregionname as Country from Locations,Stateprovince where Locations.Stateprovinceid=StateProvince.Stateprovinceid order By LocationName ASC", MyConn)
 
        Dim DS As DataSet = New DataSet()
        MyCompCommand.Fill(DS, "Locations")
 
        GrdLocation.DataSource = DS.Tables("Locations").DefaultView
        GrdLocation.DataBind()
        MyConn.Close()
    End Sub
 
 
Protected Sub GrdLocation_SelectedIndexChanging(ByVal sender As Object, ByVal e As GridViewSelectEventArgs) Handles GrdLocation.SelectedIndexChanging
        BindGrid()
        Dim LocId As Guid = CType(Me.GrdLocation.DataKeys(e.NewSelectedIndex)("LocID"), Guid)
        Dim Loc As String = Me.GrdLocation.DataKeys(e.NewSelectedIndex)("Location").ToString
        Label1.Text = Loc
        GrdLocation.Visible = False
  End Sub

Open in new window

Avatar of SaraDob

ASKER

As you said i did databind on every postback.,Sorry Not working..I'm Still getting NULL values :((

I have an observation here,:
But even before i did the databind( i mean in earlier snippet), i could get the Location(spain,Orlando etc) into the textbox, but not LocId(which was null).
So, even without doing this Databinding on every postback,i could get the location.
Comment ?!
You can get the location because the controls collection is populated, but not the DataKeys collection.
Still is odd that the DataKeys() is empty. Can you use the textbox values? It's got the side benefit of reducing ViewState size by eliminating one item from the DataKeys.
Avatar of SaraDob

ASKER

I have set Location also as datakey..Is that creating problems?
" Can you use the textbox values? It's got the side benefit of reducing ViewState size by eliminating one item from the DataKeys."
Is this what you mean txtLocId.Text=LocId ...????


<asp:GridView ID="GrdLocation" runat="server" 
DataKeyNames="LocId,Location" 
autogeneratecolumns="false" AutoGenerateSelectButton="True" 
onselectedindexchanging="GrdLocation_SelectedIndexChanging" AllowPaging="True" 
AllowSorting="True"> 
<columns> 
<asp:commandfield showselectbutton="true" 
headertext="Select Location"/> 
<asp:boundfield datafield="LocId" 
headertext="LocId"/> 
<asp:boundfield datafield="Location" 
headertext="Location"/> 
<asp:boundfield datafield="City" 
headertext="City"/> 
<asp:boundfield datafield="State" 
headertext="State"/> 
<asp:boundfield datafield="Country" 
headertext="Country"/> 
</columns> 
 
</asp:GridView> 

Open in new window

Yes, that's what I mean: Use the TextBox value to retrieve the information you need, instead of using DataKeys.
Is not that it should create problems, is just that if you already have the information you can save you trouble and ViewState space by not using DataKeys()
Avatar of SaraDob

ASKER

But the LocId is in the Gridview. as datakey.The user needs to select value from Gridview.
But isn't it in a field as well?:

<asp:boundfield datafield="LocId" headertext="LocId"/>
Avatar of SaraDob

ASKER

Yes..it is in Bound field..So i will fetch in a textbox?
SOLUTION
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
ASKER CERTIFIED SOLUTION
Avatar of Elvio Lujan
Elvio Lujan
Flag of Argentina 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
Avatar of SaraDob

ASKER

Hi lem2802:
 Its on gridview_GrdLocation_SelectedIndexChanging event..
Avatar of SaraDob

ASKER

I mean Its gridview_selectedchanging event
and how thw user "select a location"... pressing one button??
Avatar of SaraDob

ASKER

Yes , The user slects a location , by pressing a Select location button:i bind the gridview in the button _click event.
Then on selectedchanging event gridview, i select the LociD( which is hidden, set as datakey) and  (trying) to put in a textbox.
I have attached the Code snippet of on buttonclick , on selected changing and the gridview.
Please help.

 Protected Sub btnLocation_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnLocation.Click
        GrdLocation.Visible = True
        Dim MyCompCommand As SqlDataAdapter = New SqlDataAdapter("Select Locations.LocId,Locations.LocationName As Location,Locations.City,Locations.State,StateProvince.Countryregionname as Country from Locations,Stateprovince where Locations.Stateprovinceid=StateProvince.Stateprovinceid order By LocationName ASC", MyConn)
 
        Dim DS As DataSet = New DataSet()
        MyCompCommand.Fill(DS, "Locations")
 
        GrdLocation.DataSource = DS.Tables("Locations").DefaultView
        GrdLocation.DataBind()
        MyConn.Close()
    End Sub
'Selected changing event
 Sub GrdLocation_SelectedIndexChanging(ByVal sender As Object, ByVal e As GridViewSelectEventArgs)
 
        Dim LocId As Guid = CType(Me.GrdLocation.DataKeys(e.NewSelectedIndex)("LocID"), Guid)
        Dim Loc As String = Me.GrdLocation.DataKeys(e.NewSelectedIndex)("Location")
        'Label1.Text = Convert.ToString(LocId)
 
        'Dim LocId As Object = Me.GrdLocation.DataKeys(e.NewSelectedIndex)("LocID")
        'Dim s As String = LocId.ToString()
 
        'Label1.Text = s.ToString
        TxtLocation.Text = Loc.ToString
        Dim s As String = LocId.ToString()
 
        TextBox1.Text = s.ToString
        GrdLocation.Visible = False
'Asp Page of the gridview
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
                <asp:GridView ID="GrdLocation" runat="server" 
                DataKeyNames="LocId,Location"
                autogeneratecolumns="false" AutoGenerateSelectButton="True"
                onselectedindexchanging="GrdLocation_SelectedIndexChanging" AllowPaging="True" 
                    AllowSorting="True">
                <columns>
          <asp:commandfield showselectbutton="true"
            headertext="Select Location"/>
          <asp:boundfield datafield="LocId"
            headertext="LocId"/>
          <asp:boundfield datafield="Location"
            headertext="Location"/>
          <asp:boundfield datafield="City"
            headertext="City"/>
          <asp:boundfield datafield="State"
            headertext="State"/>
          <asp:boundfield datafield="Country"
            headertext="Country"/>
        </columns>
                    
                </asp:GridView>

Open in new window

ok... now try tu use the event "SelectedIndexChanged" instead "SelectedIndexChanging"
Avatar of SaraDob

ASKER

After changing everything to on SelectedChanged
i get this error
e.NewSelectedIndex is not a member of event args..
can you please look at the earlier code in selected eventchanging, and let me know what should be changed...PLEASE
use "GrdLocation.SelectedIndex" instead "e.NewSelectedIndex"
Avatar of SaraDob

ASKER

I have this error gazillion times..." Value of type 'String' cannot be converted to 'System.Guid'
Pointing to :
Dim LocId As Guid = CType(Me.GrdLocation.Rows(GrdLocation.SelectedIndex).Cells(1).Text, Guid)
If i try to correct it, the guid fetches NULL value...
I'm in need of urgent help to solve this..

not this...

Dim LocId As Guid = CType(Me.GrdLocation.Rows(
GrdLocation.SelectedIndex).Cells(1).Text, Guid)

use this...

 Dim LocId As Guid = CType(Me.GrdLocation.DataKeys(GrdLocation.SelectedIndex)("LocID"), Guid)
Avatar of SaraDob

ASKER

Well i had tried this earlier also..I did it again..But its fetching Null on GUIDs..
both SelectedIndexchanging and  Selectedindexchanged....fetched NULL values
help me...
ok... may be you have a viewstate problem... try filling the grid in the page_load... and tell me what happen...
Avatar of SaraDob

ASKER

I dont think its a view state problem...Beacuse if i try to get location( spain,orlando) from the gridview 2 nd cell, i would get that.Its only problem with GUIds
Hi

try this sample code

aspx

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="DataGrid.aspx.vb" Inherits="Data_DataGrid" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:GridView ID="GrdLocation" runat="server"
DataKeyNames="LocId,Location"
autogeneratecolumns="false" AutoGenerateSelectButton="True"
onselectedindexchanging="GrdLocation_SelectedIndexChanging" AllowPaging="True"
AllowSorting="True">
<columns>
<asp:commandfield showselectbutton="true"
headertext="Select Location"/>
<asp:boundfield datafield="LocId"
headertext="LocId"/>
<asp:boundfield datafield="Location"
headertext="Location"/>
<asp:boundfield datafield="City"
headertext="City"/>
<asp:boundfield datafield="State"
headertext="State"/>
<asp:boundfield datafield="Country"
headertext="Country"/>
</columns>
 
</asp:GridView>
        <asp:TextBox ID="TextBox1" runat="server" Width="489px"></asp:TextBox>
        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
    </form>
</body>
</html>


code behind


Partial Class Data_DataGrid
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If (Not Me.IsPostBack) Then
            Me.GrdLocation.DataSource = clsData.GetDataTable
            Me.GrdLocation.DataBind()
        End If
    End Sub

    Protected Sub GrdLocation_SelectedIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSelectEventArgs) Handles GrdLocation.SelectedIndexChanging
        Dim gid As Guid = CType(Me.GrdLocation.DataKeys(e.NewSelectedIndex)("LocId"), Guid)
        Me.TextBox1.Text = gid.ToString
        Me.TextBox2.Text = Me.GrdLocation.DataKeys(e.NewSelectedIndex)("Location").ToString


    End Sub
End Class



app_code


Imports System.Data

Public Class clsData
    Public Shared Function GetDataTable() As DataTable
        Dim dt As New DataTable
        dt.Columns.Add("LocId", GetType(Guid))
        dt.Columns.Add("Location")
        dt.Columns.Add("City")
        dt.Columns.Add("State")
        dt.Columns.Add("Country")

        dt.Rows.Add(New Object() {System.Guid.NewGuid, "aaaaa", "aaaaaaaaa", "aaaaaaaaaaaa", "aaaaaaaaaaaa"})
        dt.Rows.Add(New Object() {System.Guid.NewGuid, "bbbbb", "bbbbbbbbb", "bbbbbbbbbbbb", "bbbbbbbbbbbb"})
        dt.Rows.Add(New Object() {System.Guid.NewGuid, "ccccc", "ccccccccc", "cccccccccccc", "cccccccccccc"})
        dt.Rows.Add(New Object() {System.Guid.NewGuid, "ddddd", "ddddddddd", "dddddddddddd", "dddddddddddd"})

        Return dt
    End Function


    Public Shared Function GetDataTable1() As DataTable
        Dim dt As New DataTable
        dt.Columns.Add("LocId")
        dt.Columns.Add("Location")
        dt.Columns.Add("City")
        dt.Columns.Add("State")
        dt.Columns.Add("Country")

        dt.Rows.Add(New Object() {1, "aaaaa", "aaaaaaaaa", "aaaaaaaaaaaa", "aaaaaaaaaaaa"})
        dt.Rows.Add(New Object() {2, "bbbbb", "bbbbbbbbb", "bbbbbbbbbbbb", "bbbbbbbbbbbb"})
        dt.Rows.Add(New Object() {3, "ccccc", "ccccccccc", "cccccccccccc", "cccccccccccc"})
        dt.Rows.Add(New Object() {4, "ddddd", "ddddddddd", "dddddddddddd", "dddddddddddd"})

        Return dt
    End Function

End Class
please see this in ur code

    Dim LocId As Guid = CType(Me.GrdLocation.DataKeys(e.NewSelectedIndex)("LocID"),

 <asp:boundfield datafield="LocId"  headertext="LocId"/>

see the LocID case with LocId
Avatar of SaraDob

ASKER

Hi madhaven_Pillai,
That way code will be long and uneasy to handle it for GUIDs.
We , here as team tried for long hrs
This is the solution we finnaly agreed on and the guid problem.

Sub GrdLocation_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
' *********************************************************************
' Column #0 = Select button
' Column #1 = LocID
' Column #2 = Location
' Column #3 = Destination
' Hide the LocID column...
' *********************************************************************

If e.Row.RowType = DataControlRowType.DataRow Then
e.Row.Cells(1).Style.Add("display", "none")
ElseIf e.Row.RowType = DataControlRowType.Header Then
e.Row.Cells(1).Style.Add("display", "none")
ElseIf e.Row.RowType = DataControlRowType.Footer Then
e.Row.Cells(1).Style.Add("display", "none")
End If
End Sub

Protected Sub GrdLocation_SelectedIndexchanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles GrdLocation.SelectedIndexChanged
' *********************************************************************
' Column #0 = Select button
' Column #1 = TravelLocID
' Column #2 = Name
' Column #3 = Destination
' *********************************************************************
' Get the currently selected row...
Dim gridRow As GridViewRow = GrdLocation.SelectedRow
' Set the TextBox to the Destination value in the currently selected row...
TxtLocation.Text = gridRow.Cells(2).Text
HiddenLocid.Value = gridRow.Cells(1).Text =====This is how we got the guid in a hidden field.
GrdLocation.Visible = False
End Sub