Solved

Fetching the Primary Key from from the selected row in Gridview

Posted on 2013-02-06
13
288 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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 

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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Help with solving error related to resources file 4 35
error on the asp.net page 1 33
Resolve Dependency Issues 4 41
Advice in Xamarin 21 47
In an ASP.NET application, I faced some technical problems. In this article, I list them out and show the solutions that I found.  I hope it will be useful. Problem: After closing a pop-up window, the parent page should be refreshed automaticall…
Creating an analog clock UserControl seems fairly straight forward.  It is, after all, essentially just a circle with several lines in it!  Two common approaches for rendering an analog clock typically involve either manually calculating points with…
This video demonstrates how to create an example email signature rule for a department in a company using CodeTwo Exchange Rules. The signature will be inserted beneath users' latest emails in conversations and will be displayed in users' Sent Items…
You have products, that come in variants and want to set different prices for them? Watch this micro tutorial that describes how to configure prices for Magento super attributes. Assigning simple products to configurable: We assigned simple products…

929 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

10 Experts available now in Live!

Get 1:1 Help Now