Can't Find Value inside Gridview Extended.

Hi

I've just added a new textbox to an extended gridview control but I cannot find the control in the code behind.   This is code I've inherited from someone else but now I need to update it.  If I hardcode the values into the codebehind for 'PercentageComplete 'the insert and update queries work so I know it must be something to do with this

 Dim PercentageComplete As TextBox = TryCast(gvUnits.Rows(i).Cells(1).Controls(3), TextBox)

Open in new window



Full Gridview Extended

          <asp:Panel ID="panelEventUnits" runat="server" Visible="false">
                            <aspcc:GridViewExtended ID="gvUnits" runat="server" AutoGenerateColumns="False" CssClass="table table-condensed table-responsive" ShowFooterWhenEmpty="True"
                                DataSourceID="DSUnits" ShowFooter="True" ShowHeaderWhenEmpty="True" DataKeyNames="EVENTUNITID,PercentageComplete" GridLines="None" OnPreRender="gv_PreRender">
                                <Columns>
                                    <asp:BoundField DataField="QUALSCHEMEUNITID" HeaderText="QUALSCHEMEUNITID" SortExpression="QUALSCHEMEUNITID" Visible="False"></asp:BoundField>
                                    <asp:TemplateField HeaderText="QUALSCHEMEUNITID" SortExpression="QUALSCHEMEUNITID">
                                        <EditItemTemplate>
                                            <aspcc:DropDownListWithTitle ID="DropDownList57" runat="server" DataSourceID="DSUnitAvailable" CssClass="selectpickedr" data-live-search="true"
                                                DataTextField="UNIT" DataValueField="QUALSCHEMEUNITID" CustomProperty="QUALSCHEMEUNIT" SelectedValue='<%# Bind("QUALSCHEMEUNITID") %>'>
                                            </aspcc:DropDownListWithTitle>
                                        </EditItemTemplate>
                                        <ItemTemplate>
                                            <aspcc:DropDownListWithTitle ID="DropDownList571" runat="server" DataSourceID="DSUnitAvailable" CssClass="selectpickedr" data-live-search="true"
                                                DataTextField="UNIT" DataValueField="QUALSCHEMEUNITID" CustomProperty="QUALSCHEMEUNIT" SelectedValue='<%# Bind("QUALSCHEMEUNITID") %>'>
                                            </aspcc:DropDownListWithTitle>
                                        </ItemTemplate>
                                        <FooterTemplate>
                                            <aspcc:DropDownListWithTitle ID="DropDownList572" runat="server" AppendDataBoundItems="true" CssClass="selectpickedr"
                                                DataSourceID="DSUnitAvailable" DataTextField="UNIT" DataValueField="QUALSCHEMEUNITID" CustomProperty="QUALSCHEMEUNIT" data-live-search="true">
                                                <asp:ListItem Value="0" title="-Select-">-Select-</asp:ListItem>
                                            </aspcc:DropDownListWithTitle>
                                        </FooterTemplate>
                                    </asp:TemplateField>
                                    <asp:BoundField DataField="TYPE" HeaderText="TYPE" SortExpression="TYPE" />
                                    <asp:TemplateField HeaderText="% Complete">
                                        <EditItemTemplate>
                                            <asp:TextBox ID="txtPerComplete" runat="server" Text='<%# Bind("PercentageComplete") %>' Width="75px"></asp:TextBox>
                                        </EditItemTemplate>
                                        <FooterTemplate>
                                            <asp:TextBox ID="txtPerComplete" runat="server" Text='<%# Bind("PercentageComplete") %>' Width="75px"></asp:TextBox>
                                        </FooterTemplate>
                                        <ItemTemplate>
                                            <asp:TextBox ID="txtPerComplete" runat="server" Text='<%# Bind("PercentageComplete") %>' Width="75px"></asp:TextBox>
                                        </ItemTemplate>
                                    </asp:TemplateField>
                                </Columns>
                            </aspcc:GridViewExtended>
                            <div class="pull-right PadBtm">
                                <asp:Button ID="cmdUpateUnits" runat="server" Text="Update Units"
                                    OnClick="cmdUpateUnits_Click" CssClass="btn btn-success" />
                                <asp:Button ID="cmdResetUnits" runat="server" CssClass="btn btn-default" OnClick="cmdResetUnits_Click" Text="Cancel" />
                            </div>
                        </asp:Panel>

Open in new window



Code Behind

 Protected Sub cmdUpateUnits_Click(sender As Object, e As EventArgs) Handles cmdUpateUnits.Click
        'Create sql connection and command
        Dim con As New SqlConnection(ConnectionString)
        Dim cmd As New SqlCommand()

        For i As Integer = 0 To gvUnits.Rows.Count - 1
            Try
                Dim ID As [Object] = gvUnits.DataKeys(i).Value
                Dim QUALSCHEMEUNITID As DropDownList = TryCast(gvUnits.Rows(i).Cells(1).Controls(1), DropDownList)
                Dim PercentageComplete As TextBox = TryCast(gvUnits.Rows(i).Cells(1).Controls(3), TextBox)

                Dim strUpdate As String = "UPDATE I_TRAINEE_EVENTS_UNITS SET QUALSCHEMEUNITID = @QUALSCHEMEUNITID,PercentageComplete = @PercentageComplete  WHERE(EVENTUNITID = @ID)"
                cmd.CommandType = CommandType.Text
                cmd.CommandText = strUpdate.ToString()
                cmd.Parameters.Clear()
                cmd.Parameters.AddWithValue("@QUALSCHEMEUNITID", QUALSCHEMEUNITID.SelectedValue)
                cmd.Parameters.AddWithValue("@PercentageComplete", PercentageComplete.Text)
                cmd.Parameters.AddWithValue("@ID", ID.ToString())
                cmd.Connection = con
                con.Open()
                cmd.ExecuteNonQuery()
            Catch ex As SqlException
                Dim errorMsg As String = "Error in Updating"
                errorMsg &= ex.Message
                Throw New Exception(errorMsg)
            Finally
                con.Close()
            End Try

Open in new window

EdAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Lokesh B RDeveloperCommented:
Hi,

Replace For loop with below FOREACH loop.

Use FindControl() to find.

For Each row As GridViewRow In GridView1.Rows
	If row.RowType = DataControlRowType.DataRow Then
		Try
			Dim ID = GridView1.DataKeys(row.RowIndex).Value

			' Change the DropDownList ID based on your requirement
			Dim QUALSCHEMEUNITID As DropDownList = DirectCast(row.FindControl("DropDownList57"), DropDownList)

			' Change the TextBox ID based on your requirement
			Dim PercentageComplete As TextBox = DirectCast(row.FindControl("txtPerComplete"), TextBox)

			Dim strUpdate As String = "UPDATE I_TRAINEE_EVENTS_UNITS SET QUALSCHEMEUNITID=@QUALSCHEMEUNITID, PercentageComplete=@PercentageComplete WHERE(EVENTUNITID=@ID)"
			cmd.CommandType = CommandType.Text
			cmd.CommandText = strUpdate.ToString()
			cmd.Parameters.Clear()
			cmd.Parameters.AddWithValue("@QUALSCHEMEUNITID", QUALSCHEMEUNITID.SelectedValue)
			cmd.Parameters.AddWithValue("@PercentageComplete", PercentageComplete.Text)
			cmd.Parameters.AddWithValue("@ID", ID.ToString())
			cmd.Connection = con
			con.Open()
			cmd.ExecuteNonQuery()
		Catch ex As SqlException
			Dim errorMsg As String = "Error in Updating"
			errorMsg += ex.Message
			Throw New Exception(errorMsg)
		Finally
			con.Close()
		End Try
	End If
Next

Open in new window

0
EdAuthor Commented:
I'm getting an error now

Object reference not set to an instance of an object.
  Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

 Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:



Line 294:
Line 295:        Try
Line 296:            Dim QUALSCHEMEID As DropDownList = TryCast(gvUnits.FooterRow.Cells(1).Controls(1), DropDownList)
Line 297:            Dim PercentageComplete As Integer = 40
Line 298:

 






Hers the full code for the button click event.

    Protected Sub cmdUpateUnits_Click(sender As Object, e As EventArgs) Handles cmdUpateUnits.Click
        'Create sql connection and command
        Dim con As New SqlConnection(ConnectionString)
        Dim cmd As New SqlCommand()

        For Each row As GridViewRow In gvUnits.Rows
            If row.RowType = DataControlRowType.DataRow Then
                Try
                    Dim ID = gvUnits.DataKeys(row.RowIndex).Value

                    ' Change the DropDownList ID based on your requirement
                    Dim QUALSCHEMEUNITID As DropDownList = DirectCast(row.FindControl("DropDownList57"), DropDownList)

                    ' Change the TextBox ID based on your requirement
                    Dim PercentageComplete As TextBox = DirectCast(row.FindControl("txtPerComplete"), TextBox)

                    Dim strUpdate As String = "UPDATE I_TRAINEE_EVENTS_UNITS SET QUALSCHEMEUNITID=@QUALSCHEMEUNITID, PercentageComplete=@PercentageComplete WHERE(EVENTUNITID=@ID)"
                    cmd.CommandType = CommandType.Text
                    cmd.CommandText = strUpdate.ToString()
                    cmd.Parameters.Clear()
                    cmd.Parameters.AddWithValue("@QUALSCHEMEUNITID", QUALSCHEMEUNITID.SelectedValue)
                    cmd.Parameters.AddWithValue("@PercentageComplete", PercentageComplete.Text)
                    cmd.Parameters.AddWithValue("@ID", ID.ToString())
                    cmd.Connection = con
                    con.Open()
                    cmd.ExecuteNonQuery()
                Catch ex As SqlException
                    Dim errorMsg As String = "Error in Updating"
                    errorMsg += ex.Message
                    Throw New Exception(errorMsg)
                Finally
                    con.Close()
                End Try
            End If
        Next



        Try
            Dim QUALSCHEMEID As DropDownList = TryCast(gvUnits.FooterRow.Cells(1).Controls(1), DropDownList)
            Dim PercentageComplete As Integer = 40

            If QUALSCHEMEID.SelectedValue.ToString() <> "0"c.ToString() Then

                Dim strUpdate As String = "INSERT INTO I_TRAINEE_EVENTS_UNITS (QUALSCHEMEUNITID, EVENTID, PercentageComplete) VALUES(@QUALSCHEMEUNITID,@EVENTID,@PercentageComplete)"
                cmd.CommandType = CommandType.Text
                cmd.CommandText = strUpdate.ToString()
                cmd.Parameters.Clear()
                cmd.Parameters.AddWithValue("@EVENTID", dvEvent.SelectedValue)
                cmd.Parameters.AddWithValue("@QUALSCHEMEUNITID", QUALSCHEMEID.SelectedValue)
                cmd.Parameters.AddWithValue("@PercentageComplete", PercentageComplete.ToString)
                cmd.Connection = con
                con.Open()
                cmd.ExecuteNonQuery()
            End If
        Catch ex As SqlException
            Dim errorMsg As String = "Error in Insert"
            errorMsg &= ex.Message
            Throw New Exception(errorMsg)
        Finally
            con.Close()
        End Try

        gvUnits.DataBind()
    End Sub

Open in new window

0
Lokesh B RDeveloperCommented:
Hi,

Change this line and try

Try
      Dim QUALSCHEMEID As DropDownList = DirectCast(GridView1.FooterRow.FindControl("DropDownList572"), DropDownList)
      Dim PercentageComplete As Integer = 40

      If QUALSCHEMEID IsNot Nothing AndAlso QUALSCHEMEID.SelectedValue.ToString() <> "0"C.ToString() Then

            Dim strUpdate As String = "INSERT INTO I_TRAINEE_EVENTS_UNITS (QUALSCHEMEUNITID, EVENTID, PercentageComplete) VALUES(@QUALSCHEMEUNITID,@EVENTID,@PercentageComplete)"
            cmd.CommandType = CommandType.Text
            cmd.CommandText = strUpdate.ToString()
            cmd.Parameters.Clear()
            cmd.Parameters.AddWithValue("@EVENTID", dvEvent.SelectedValue)
            cmd.Parameters.AddWithValue("@QUALSCHEMEUNITID", QUALSCHEMEID.SelectedValue)
            cmd.Parameters.AddWithValue("@PercentageComplete", PercentageComplete.ToString())
            cmd.Connection = con
            con.Open()
            cmd.ExecuteNonQuery()
      End If
Catch ex As SqlException
      Dim errorMsg As String = "Error in Insert"
      errorMsg += ex.Message
      Throw New Exception(errorMsg)
Finally
      con.Close()
End Try

gvUnits.DataBind()
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
EdAuthor Commented:
Great thanks.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
ASP.NET

From novice to tech pro — start learning today.