Click here to Skip to main content
15,904,156 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Whenever I add anything to TextBox2 and execute the statement below I get this error:

Object reference not set to an instance of an object.


Code:
VB
Try
    connStr = "connectionstring works"
    cmdStr = "INSERT INTO posts (post) VALUES @post;"
    Using conn As New SqlConnection(connStr)
        Using cmd As New SqlCommand(cmdStr, conn)
            conn.Open()
            cmd.Parameters.AddWithValue("@post", TextBox2.Text)
            cmd.ExecuteNonQuery()
            conn.Close()
            cmd.Dispose()
            conn.Dispose()
        End Using
    End Using
Catch ex As Exception
    TextBox6.Text = ex.ToString()
End Try


I have some jQuery code that messes with TextBox2.

JavaScript
    <script src="../Scripts/jquery-1.4.1.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {
           $("#<%= TextBox2.ClientID %>").keypress(function (e) {
                var maxCount = 500;
                var strCount = $("#<%= TextBox2.ClientID %>").val().length;
                if (strCount < maxCount) {
                    $("#<%= TextBox3.ClientID %>").val(strCount);
                    $("#<%= Label4.ClientID %>").text("");
                    $("#<%= Button4.ClientID %>").trigger('click');
                } else {
                    e.preventDefault();
                    $("#<%= TextBox3.ClientID %>").val("(Over 500 Keypress Limit)");
                    $("#<%= Label4.ClientID %>").text("_____Click anywhere on TextBox to Edit______");
                }
            });
      });
</script>
Posted
Updated 24-Jun-14 9:32am
v5
Comments
PIEBALDconsult 24-Jun-14 16:01pm    
Which line does the debugger say has the problem?

This may not be the actual answer to the question but below three statements are not required
VB
conn.Close()
cmd.Dispose()
conn.Dispose()

For better explanation see this : http://msdn.microsoft.com/en-us/library/htd05whh.aspx[^]

Further, i recommend you to remove the Try catch blocks,they are not meant for such scenarios. Put the debugger at first line of code and step through it. Debugger will stop on the line where the error is. Look at the variables involved into it. See the best answer to this error : object reference not set to an instance of an object. in c#[^]

Regards..
 
Share this answer
 
Replace:
SQL
INSERT INTO posts (post) VALUES @post;

with:
SQL
INSERT INTO posts (post) VALUES (@post);


The rest part of code looks good.

I'd strongly recommend to verify ConnectionString[^].
 
Share this answer
 
Comments
Teledextri 24-Jun-14 15:56pm    
Not my SQL Statement.
Teledextri 24-Jun-14 16:01pm    
Not my Connectionstring

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900