Solved

Fetching the Primary Key from from the selected row in Gridview

Posted on 2013-02-06
13
287 Views
Last Modified: 2013-02-06
I have a scenario where I conditionally need to determine whether the insert or update statement needs to be fired based on wheter Event_Key already exists in database.

The error occurs at        
selectedID = GVViewEvents.SelectedRow.Cells(0).Text
Error: Object reference not set to an instance of an object.


Gridview code:
<asp:GridView ID="GVViewEvents" DataSourceID="sdsEvents" DataKeyNames="Linea,Event_Key" runat="server" Height="186px" Width="713px" CellPadding="4" ForeColor="#333333" GridLines="None" BorderStyle="Solid" BorderWidth="2px" BorderColor="#D8D8D8" PageSize="4" AutoGenerateColumns="False">
                    <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White"   />
                    <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
                    <Columns>                                     
                        <asp:CommandField ShowEditButton="True" EditText="Update"   />                        
                        <asp:BoundField DataField="Event_Key" HeaderText="Event_Key" InsertVisible="true" SortExpression="Event_Key" Visible="true" ReadOnly="true" />
                        <asp:BoundField DataField="Linea" HeaderText="Linea" SortExpression="Linea" ReadOnly="true" />
                        <asp:TemplateField HeaderText="QTY de Lineas de Ensamble" SortExpression="Total_Qty">
                            <EditItemTemplate>
                                <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Total_Qty") %>' Width="25px"></asp:TextBox>
                            </EditItemTemplate>
                            <ItemTemplate>
                                <asp:Label ID="Label1" runat="server" Text='<%# Bind("Total_Qty") %>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                    <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
                    <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
                    <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" HorizontalAlign="Left" />
                    <EditRowStyle BackColor="#F7F6F3" ForeColor="#333333" />
                    <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
                </asp:GridView>

Open in new window


VB Code:
Private Sub gridview1_RowUpdated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdatedEventArgs) Handles GVViewEvents.RowUpdated

        Dim determineSP As String
        Dim sqlStr As String

        Dim sConn As String = ConfigurationManager.ConnectionStrings("BusDevConnectionString").ToString
        Dim myConnection As SqlConnection = New SqlConnection(sConn)
 
        sqlStr = ""
        Dim selectedID As String
        selectedID = GVViewEvents.SelectedRow.Cells(0).Text

        determineSP = "SELECT * FROM Lenovo_events WHERE Event_Key = '" & selectedID & "'"

        If selectedID Is Nothing Then
            sqlStr = "insert into lenovo_events values (@event_date,@line_key, @shift_key, @total_qty, 0,0)"
        Else
            sqlStr = "update lenovo_events set total_qty = @total_qty where event_key = @event_key"
        End If

        GVViewEvents.DataBind()
    End Sub

Open in new window


Thanks for your time!
0
Comment
Question by:JessyRobinson1234
  • 5
  • 4
  • 4
13 Comments
 
LVL 23

Expert Comment

by:Ioannis Paraskevopoulos
ID: 38858854
Hi,

You have to reference it through the sender argument. I think it goes something like :

selectedID = CType(sender,GridView).SelectedRow.Cells(0).Text

Open in new window


Giannis
0
 
LVL 23

Expert Comment

by:Ioannis Paraskevopoulos
ID: 38858869
Since you are going to refernce it later in your code again, you could do the following:

Private Sub gridview1_RowUpdated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdatedEventArgs) Handles GVViewEvents.RowUpdated

        Dim determineSP As String
        Dim sqlStr As String

        Dim sConn As String = ConfigurationManager.ConnectionStrings("BusDevConnectionString").ToString
        Dim myConnection As SqlConnection = New SqlConnection(sConn)
 
        sqlStr = ""
        Dim selectedID As String

        Dim gv As GridView = CType(sender, GridView)
        selectedID = gv.SelectedRow.Cells(0).Text

        determineSP = "SELECT * FROM Lenovo_events WHERE Event_Key = '" & selectedID & "'"

        If selectedID Is Nothing Then
            sqlStr = "insert into lenovo_events values (@event_date,@line_key, @shift_key, @total_qty, 0,0)"
        Else
            sqlStr = "update lenovo_events set total_qty = @total_qty where event_key = @event_key"
        End If

        gv.DataBind()
    End Sub

Open in new window


Giannis
0
 
LVL 83

Expert Comment

by:CodeCruiser
ID: 38858978
Change this

selectedID = GVViewEvents.SelectedRow.Cells(0).Text

to

selectedID = e.OldValues(0)

or

selectedID = e.NewValues(0)
0
 

Author Comment

by:JessyRobinson1234
ID: 38858983
Hi, thak you. My error:

selectedID = gv.SelectedRow.Cells(0).Text
Object reference not set to an instance of an object.
0
 
LVL 23

Expert Comment

by:Ioannis Paraskevopoulos
ID: 38859138
Hi,

Change to this:

selectedID = gv.Rows(e.RowIndex).Cells(0).Text

Open in new window


Thanks,
Giannis
0
 
LVL 23

Expert Comment

by:Ioannis Paraskevopoulos
ID: 38859152
And it seems it should work without having the gv, so you could have it your way:

selectedID = GVViewEvents.Rows(e.RowIndex).Cells(0).Text

Open in new window


Giannis
0
Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

 

Author Comment

by:JessyRobinson1234
ID: 38859203
Rowindex is not a member of System.Web.UI.Webcontrols.GridViewUpdatedEventArgs
0
 
LVL 83

Expert Comment

by:CodeCruiser
ID: 38859633
Did you have a look at http:#a38858978 ?
0
 

Author Comment

by:JessyRobinson1234
ID: 38860596
CodeCruiser, thanks for pointing it out, I did not. I tried your suggestion selectedID = e.OldValues(0) and based on the attached screenshot it's assigning "15" as selectedID. I would like to fetch the event_key which is in this case 17.

selectedIDCan you assist?
0
 
LVL 23

Accepted Solution

by:
Ioannis Paraskevopoulos earned 500 total points
ID: 38860753
Can you check the value of e. keys(0) . It might be what you want.
0
 
LVL 83

Expert Comment

by:CodeCruiser
ID: 38861322
By the way, you just had to adjust the columnindex with my technique.
0
 

Author Comment

by:JessyRobinson1234
ID: 38861351
I agree, I should give you half the points. How can I do that?
0
 
LVL 83

Expert Comment

by:CodeCruiser
ID: 38862043
Don't worry :-)
0

Featured Post

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Just a quick little trick I learned recently.  Now that I'm using jQuery with abandon in my asp.net applications, I have grown tired of the following syntax:      (CODE) I suppose it just offends my sense of decency to put inline VBScript on a…
The ECB site provides FX rates for major currencies since its inception in 1999 in the form of an XML feed. The files have the following format (reducted for brevity) (CODE) There are three files available HERE (http://www.ecb.europa.eu/stats/exch…
It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.
Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…

708 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now