Click here to Skip to main content
13,552,926 members
Rate this:
 
Please Sign up or sign in to vote.
Dear gurus,

I am trying to insert datagridview rows to mysql table using the below code in vb.net but getting the subjected error, dont know where I am making mistake? pls help

What I have tried:

Try
           Dim product, qty, price, total, desc, billno As String
           For i As Integer = 0 To Me.DataGridView1.Rows.Count - 1
               If DataGridView1.RowCount > 0 AndAlso DataGridView1.CurrentRow IsNot Nothing Then
                   'datatype integer
                   product = Convert.ToInt32(Me.DataGridView1.Rows(i).Cells(1).Value.ToString())
                   'datatype double
                   qty = Convert.ToDouble(Me.DataGridView1.Rows(i).Cells(2).Value.ToString())
                   price = Convert.ToDouble(Me.DataGridView1.Rows(i).Cells(3).Value.ToString())
                   total = Convert.ToDouble(Me.DataGridView1.Rows(i).Cells(4).Value.ToString())
                   'datatype varchar
                   desc = Me.DataGridView1.Rows(i).Cells(5).Value.ToString()
               End If
               billno = txtbillno.Text
               sqL = "INSERT INTO `dailysale`(`billno`,`customer_id`, `product_id`, `qty`, `price`, `total`, `description`) VALUES('" & billno & ",''" & txtCustomer.Tag & "', '" & product & "', '" & qty & "', '" & price & "', '" & total & "', '" & desc & "')"
           Next
           sqL &= "INSERT INTO `customer_payments`(`customer_id`, `billno`, `cdate`, `bill_amount`, `paid_amount`, `discount`, `ret_amount`, `balance`) VALUES ('" &
           txtCustomer.Tag & "','" & txtbillno.Text & "','" & DateTimePicker1.Value & "','" & Convert.ToDouble(txtbill_amount.Text) & "','" & Convert.ToDouble(txtpaid_amount.Text) & "','" & Convert.ToDouble(txtdiscount.Text) & "','" & Convert.ToDouble(txtret_amount.Text) & "','" & Convert.ToDouble(txttotalbalance.Text) & "')"
           ConnDB()
           cmd = New MySqlCommand(sqL, conn)
           cmd.ExecuteNonQuery()

           MsgBox("New Bill successfully created.", MsgBoxStyle.Information, "Create Bill")
       Catch ex As Exception
           MsgBox(ex.ToString)
       Finally
           cmd.Dispose()
           conn.Close()
       End Try
Posted 19-May-17 6:36am
Updated 19-May-17 12:31pm
v2
Comments
NotPolitcallyCorrect 19-May-17 12:39pm
   
The error message tells you what the problem is and where it happens.
nyt1972 19-May-17 12:43pm
   
'datatype integer
product = Convert.ToInt32(Me.DataGridView1.Rows(i).Cells(1).Value.ToString())
'datatype integer
desc = Me.DataGridView1.Rows(i).Cells(5).Value.ToString()

Show error in these two lines
Richard-MacCutchan 19-May-17 12:47pm
   
Row(i) or Cells(1) or (5) do not exist, or contain null.
nyt1972 19-May-17 12:52pm
   
Cells(1) containt value and Cells(5) too. but even then getting this error
Richard-MacCutchan 19-May-17 12:54pm
   
Then use your debugger to find out exactly which item is null at this point. There is no way anyone here can do it for you.
Richard-MacCutchan 19-May-17 12:46pm
   
With such badly written code it is little wonder. You are selecting items without any check as to their validity and trying to convert them to numeric types. You need to learn how to write proper validation checking, and using proper parameterised queries for SQL statements. And finally you are posting a success message without checking that your INSERT actually completed successfully.
nyt1972 19-May-17 13:27pm
   
Changed code to below but now records are not stored in database
Try
            ConnDB()
            cmd = New MySqlCommand(sqL, conn)
            For i As Integer = 0 To Me.DataGridView1.Rows.Count - 1
                sqL = "INSERT INTO `dailysale`(`billno`,`customer_id`, `product_id`, `qty`, `price`, `total`, `description`) VALUES('@billno','@custid''@product', '@qty', '@price', '@total', '@desc')"
                'datatype integer
                With cmd
                    .Parameters.Clear()
                    .Parameters.AddWithValue("@billno", txtbillno.Text)
                    .Parameters.AddWithValue("@custid", txtCustomer.Tag)
                    .Parameters.AddWithValue("@product", Me.DataGridView1.Rows(i).Cells(1).Value)
                    .Parameters.AddWithValue("@qty", Me.DataGridView1.Rows(i).Cells(2).Value)
                    .Parameters.AddWithValue("@price", Me.DataGridView1.Rows(i).Cells(3).Value)
                    .Parameters.AddWithValue("@total", Me.DataGridView1.Rows(i).Cells(4).Value)
                    .Parameters.AddWithValue("@desc", Me.DataGridView1.Rows(i).Cells(5).Value)
                End With
            Next
            sqL &= "INSERT INTO `customer_payments`(`customer_id`, `billno`, `cdate`, `bill_amount`, `paid_amount`, `discount`, `ret_amount`, `balance`) VALUES ('" &
            txtCustomer.Tag & "','" & txtbillno.Text & "','" & DateTimePicker1.Value & "','" & txtbill_amount.Text & "','" & txtpaid_amount.Text & "','" & txtdiscount.Text & "','" & txtret_amount.Text & "','" & txttotalbalance.Text & "')"

            cmd.ExecuteNonQuery()

            MsgBox("New Bill successfully created.", MsgBoxStyle.Information, "Create Bill")
        Catch ex As Exception
            MsgBox(ex.ToString)
        Finally
            cmd.Dispose()
            conn.Close()
        End Try
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

This is one of the most common problems we get asked, and it's also the one we are least equipped to answer, but you are most equipped to answer yourself.

Let me just explain what the error means: You have tried to use a variable, property, or a method return value but it contains null - which means that there is no instance of a class in the variable.
It's a bit like a pocket: you have a pocket in your shirt, which you use to hold a pen. If you reach into the pocket and find there isn't a pen there, you can't sign your name on a piece of paper - and you will get very funny looks if you try! The empty pocket is giving you a null value (no pen here!) so you can't do anything that you would normally do once you retrieved your pen. Why is it empty? That's the question - it may be that you forgot to pick up your pen when you left the house this morning, or possibly you left the pen in the pocket of yesterdays shirt when you took it off last night.

We can't tell, because we weren't there, and even more importantly, we can't even see your shirt, much less what is in the pocket!

Back to computers, and you have done the same thing, somehow - and we can't see your code, much less run it and find out what contains null when it shouldn't.
But you can - and Visual Studio will help you here. Run your program in the debugger and when it fails, VS will show you the line it found the problem on. You can then start looking at the various parts of it to see what value is null and start looking back through your code to find out why. So put a breakpoint at the beginning of the method containing the error line, and run your program from the start again. This time, VS will stop before the error, and let you examine what is going on by stepping through the code looking at your values.

But we can't do that - we don't have your code, we don't know how to use it if we did have it, we don't have your data. So try it - and see how much information you can find out!
  Permalink  
Comments
nyt1972 19-May-17 13:39pm
   
With the changed code now its not showing any error but records are not stored in database
NotPolitcallyCorrect 19-May-17 13:48pm
   
Learning how to use the debugger to debug your code isn't really an optional skill that you can choose not to learn.
OriginalGriff 19-May-17 14:00pm
   
+5 - if I could. :thumbsup: will have to do, I'm afraid.
NotPolitcallyCorrect 19-May-17 14:29pm
   
Thanks. No worries. Feel free to to include that bit of "wisdom" in your answer. :-)
OriginalGriff 19-May-17 13:59pm
   
As NotPoliticallyCorrect says, learning to debug your code is not optional: any more than not learning to put fuel in your car is optional if you want to drive any real distance.
Get rid of the string concatenation and use a parameterised query, and use the debugger to find out exactly what is happening when your code runs.
Learning how to find the faults in your code is a major part of learning to code - it's a skill that transfers into the real world, and will help you all your life. But like all skills, you only improve it by using it - and it's a lot easier to learn on a trivial code fragment like that than it is on a 2,000,000 line behemoth...
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 2

Not a solution to your question, but a solution to another problem you have.
You should never build an SQL query by concatenating with user inputs, it is named "SQL injection", it is dangerous for your database and error prone.
A single quote in a name and your program crash. If a user input like "Brian O'Conner" can crash your app, it is an SQL injection vulnerability.
SQL injection - Wikipedia[^]
SQL Injection[^]
Quote:
Datagridview object reference not set to an instance of an object

For some reason, your code fail create to an instance of a Datagridview object in a variable. This is not a problem until you try to use that variable.
Use the debugger and you will see how your code perform, it helps to locate problems and their reasons.

When you don't understand what your code is doing or why it does what it does, the answer is debugger.
Use the debugger to see what your code is doing. Just set a breakpoint and see your code performing, the debugger allow you to execute lines 1 by 1 and to inspect variables as it execute, it is an incredible learning tool.

Debugger - Wikipedia, the free encyclopedia[^]
Visual Basic / Visual Studio Video Tutorial - Basic Debugging - YouTube[^]
Visual Basic .NET programming for Beginners - Breakpoints and Debugging Tools[^]
The debugger is here to show you what your code is doing and your task is to compare with what it should do.
There is no magic in the debugger, it don't find bugs, it just help you to. When the code don't do what is expected, you are close to a bug.
  Permalink  
Comments
nyt1972 20-May-17 7:19am
   
Thank you all for your replies and helping me, I tried my level best but facing new new errors so finally uploaded my project if anyone help me then.

Here is my project
ppolymorphe 20-May-17 8:42am
   
Use Improve question to update your question.
or open new question.
I fear no one will want to load your project, so you have to do first job of locating problems in your code and ask questions on this code with exact error messages and position of errors.
nyt1972 20-May-17 13:53pm
   
http://ansicollege.net/vbcode/error.png

This the error I get.

Following is the code line I get error in

dgvcc = DirectCast(DataGridView1.Rows(i).Cells(1), DataGridViewComboBoxCell)
.Parameters.AddWithValue("@product", dgvcc.Value)

I store values in combobox of Datagridview, product_id datatype in database is int
ppolymorphe 20-May-17 14:31pm
   
Use Improve question to update your question.
So that everyone can pay attention to this information.

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

  Print Answers RSS
Top Experts
Last 24hrsThis month


Advertise | Privacy |
Web03 | 2.8.180515.1 | Last Updated 19 May 2017
Copyright © CodeProject, 1999-2018
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100