1

I am trying to learn how to do this .NET frameworks for my job and what not..... I can't figure why it isn't working.

Error occurs here:

myCommand.Connection.Open()

I am assuming it is because of how I am doing....

Dim idbox As TextBox = E.Item.Cells(numCols - 1).Controls(0) myCommand.Parameters("@Id").Value = Integer.Parse(idbox.Text)

Source:

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="System.Data.OleDb" %>
<html>
<script language="VB" runat="server">
   Dim myConnection As SqlConnection
   '  Create a connection to the "pubs" SQL database located on the 
   ' local computer. 
    Sub Page_Load(Src As Object, E As EventArgs)
        If Session("Admin") <> True Then
            Response.Redirect("login.aspx")
        Else

            Dim myConnection As SqlConnection = New SqlConnection("CONNECTION INFO")
            ' Determine whether this page is a postback. If it is not a
            ' postback, call BindGrid.
            If Not IsPostBack Then
                Dim dbconn As OleDbConnection
                Dim sql As String
                Dim dbcomm As OleDbCommand
                Dim dbread As OleDbDataReader
                dbconn = New OleDbConnection("CONNECTION INFO")
                dbconn.Open()
                sql = "SELECT Name FROM TestData"
                dbcomm = New OleDbCommand(sql, dbconn)
                dbread = dbcomm.ExecuteReader()
                DropDownList1.Items.Clear()
                While dbread.Read
                    DropDownList1.Items.Add(dbread(0))
                End While
                dbread.Close()
                dbconn.Close()
                BindGrid()
            End If
        End If
    End Sub

   ' Create an index to the DataGrid row that is clicked and 
   ' call BindGrid.
   Sub MyDataGrid_Edit(sender As Object, E As DataGridCommandEventArgs)
      MyDataGrid.EditItemIndex = CInt(E.Item.ItemIndex)
      BindGrid()
   End Sub

   ' Cancel resets the index to the row's previous settings.
   Sub MyDataGrid_Cancel(sender As Object, E As DataGridCommandEventArgs)
      MyDataGrid.EditItemIndex = -1
      BindGrid()
   End Sub

   ' When the  Update link is clicked, build a SQL UPDATE command,    
   ' connect to the database, update the row's information in the 
   ' database, and rebind the DataGrid to show the updated information.
   Public Sub MyDataGrid_Update(sender As Object, _
      E As DataGridCommandEventArgs)
        Dim updateCmd As String = "UPDATE TestData SET AdoptedNum = @AdoptedNum, PrecinctNum = @PrecinctNum WHERE Id = @Id"
        Dim myCommand As SqlCommand = New SqlCommand(updateCmd, myConnection)
        myCommand.Parameters.Add(New SqlParameter("@Name", SqlDbType.VarChar))
        myCommand.Parameters.Add(New SqlParameter("@PrecinctNum", SqlDbType.Int))
        myCommand.Parameters.Add(New SqlParameter("@AdoptedNum", SqlDbType.Int))
        myCommand.Parameters.Add(New SqlParameter("@Id", SqlDbType.Int))

      ' Initialize the SqlCommand "@ID" parameter to the ID of the row 
        ' that must be clicked.
        Dim numCols As Integer = E.Item.Cells.Count
        Dim i As Integer
        Dim colvalue As String
        Dim txtBox As TextBox
        Dim idbox As TextBox = E.Item.Cells(numCols - 1).Controls(0)
        myCommand.Parameters("@Id").Value = Integer.Parse(idbox.Text)
      ' Create an array of column names.
        Dim cols() As String = {"@Name", "@PrecinctNum", "@AdoptedNum", "@Id"}
      ' Skipping the first, second, and last columns, iterate through the 
      ' columns, checking for empty values. If an empty value is found, 
      '  display a message box. Also initialize the SqlCommand 
      ' parameter values.
        For i = 2 To numCols - 1
            txtBox = E.Item.Cells(i).Controls(0)
            colvalue = txtBox.Text
            If (i < numCols And colvalue = "") Then
                Message.InnerHtml = "ERROR: Null values not allowed for " _
                   & "Author ID, Name or Phone"
                Message.Style("color") = "red"
                Exit Sub
            End If
            myCommand.Parameters(cols(i - 1)).Value = colvalue
        Next i

        ' Connect to the database and update the information.
        myCommand.Connection.Open()
        ' Test  whether the data was updated, and display the 
        ' appropriate message to the user.
        Try
            myCommand.ExecuteNonQuery()
            Message.InnerHtml = "<b>Record Updated.</b><br>"
            MyDataGrid.EditItemIndex = -1
        Catch ex As SqlException
            If ex.Number = 2627 Then
                Message.InnerHtml = "ERROR: A record already exists" _
                   & " with the same primary key"
            Else
                Message.InnerHtml = "ERROR: Could not update record," _
                   & " please ensure the fields are correctly filled out."
                Message.Style("color") = "red"
            End If
        End Try

        ' Close the connection.
        myCommand.Connection.Close()
        ' Rebind the DataGrid to show the updated information.
        BindGrid()
   End Sub

   ' The BindGrid procedure connects to the database and implements
    ' a SQL SELECT query to get all the data in the "Authors" tablea.
   Public Sub BindGrid() 
        Dim myConnection As SqlConnection = _
           New SqlConnection("CONNECTION INFO")
        Dim myCommand As SqlDataAdapter = New SqlDataAdapter("SELECT *" _
           & " FROM TestData WHERE Name='" & DropDownList1.SelectedValue & "'", myConnection)
      Dim ds As DataSet= New DataSet()
      myCommand.Fill(ds)
      MyDataGrid.DataSource = ds
        MyDataGrid.DataBind()
   End Sub

    Protected Sub MyDataGrid_SelectedIndexChanged(sender As Object, e As System.EventArgs)

    End Sub

    Sub DropDownList1_SelectedIndexChanged(sender As Object, e As EventArgs)
        BindGrid()
    End Sub
</script>

<body style="font: 10pt verdana">
   <form id="Form1" runat="server"><center>
      <h3><font face="Verdana">Updating a Row of Data.</font></h3>
      <span id="Message" EnableViewState="false" 
         style="font:arial 11pt;" runat="server"/><p>
             <asp:DropDownList ID="DropDownList1"  runat="server" AutoPostBack="True" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
             </asp:DropDownList>
      <ASP:DataGrid id="MyDataGrid" runat="server"
         Width="800"
         BackColor="#ccccff" 
         BorderColor="black"
         ShowFooter="false" 
         CellPadding=3 
         CellSpacing="0"
         Font-Name="Verdana"
         Font-Size="8pt"
         HeaderStyle-BackColor="#aaaadd"
         OnEditCommand="MyDataGrid_Edit"
         OnCancelCommand="MyDataGrid_Cancel"
         OnUpdateCommand="MyDataGrid_Update"
      >
      <Columns>
         <ASP:EditCommandColumn EditText="Edit" CancelText="Cancel" 
            UpdateText="Update"/>
      </Columns>
   </ASP:DataGrid>
   </center>
</form>
</body>
</html>
3
  • please always post the exact error message. Commented Aug 12, 2011 at 16:44
  • Please come up with specific issue. Only post code that is relevant to your problem instead complete code. Commented Aug 12, 2011 at 16:48
  • "Object reference not set to an instance of an object." it occurs when you are trying to update a row of data. Commented Aug 12, 2011 at 16:51

2 Answers 2

3

I suspect the problem is you define but never initialize the instance variable myConnection. You define and instantiate a local variable of the same name within the Page_Load function, but that is a distinct and different object than your instance variable.

In your Page_Load, if you change this:

Dim myConnection As SqlConnection = New SqlConnection("CONNECTION INFO")

to this:

myConnection As SqlConnection = New SqlConnection("CONNECTION INFO")

then your instance variable should be initialized and ready for use in your MyDataGrid_Update event handler.

Sign up to request clarification or add additional context in comments.

3 Comments

I assume you're passing a real connection string, and not literally "CONNECTION INFO", of course :)
Lol. Yes, I thought giving out all the passwords and what not out is bad. :P And that worked wonders! Now I have to deal with the logic error! Lol. Nothing I can't do. Thank you very much, Sir!
I figured that was the case with the connection string - but hey I had to ask - ya never know! :) Glad this resolved the issue. If you click the checkmark-shaped image next to this answer, it will "accept" it as the answer that solved the issue. Accepting answers is good stackoverflow-citizenship.
0

Did this even compile? This wont work because your code has a bug.

SqlCommand won't support myCommand.Connection.Open()

3 Comments

Seems to have compiled. It works up to the point of pressing "Update" then to crashes. And this is actually a code from a site I found demostrating it. I only changed a few things. How would I go about fixing this bug?
Nothing wrong with that. Connection is the property of type sqlConnection. If it's set (and it is in the constructor), you can call methods on the object it returns
with what simon? i dont get you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.