You are here:

C#/Insert blank/null datagridview cell into database table

Advertisement


Question
I have created a datagridview with three columns in designer.using the below code I can save inputs into table. I want to leave any of the columns cell blank and insert zero in the database table. Please help me to get started with .
Thanks


'Create Command object
       Dim nonqueryCommand As OleDbCommand = thisConnection.CreateCommand()

       Try
         ' Open Connection
         thisConnection.Open()
         Console.WriteLine("Connection Opened")

         ' Create INSERT statement with named parameters
         nonqueryCommand.CommandText = _
         "INSERT  INTO Table3 (Col1, Col2,col3) VALUES (@Col1, @Col2,@col3)"

         nonqueryCommand.Prepare()

         ' Data to be inserted
         For Each row As DataGridViewRow In DataGridView1.Rows
         If Not row.IsNewRow Then

         nonqueryCommand.Parameters.Add("@Col1", OleDbType.VarChar, 50)
         nonqueryCommand.Parameters.Add("@Col2", OleDbType.VarChar, 50)
         nonqueryCommand.Parameters.Add("@Col3", OleDbType.VarChar, 50)


         nonqueryCommand.Parameters("@Col1").Value = row.Cells(0).Value.ToString()
         nonqueryCommand.Parameters("@Col2").Value = row.Cells(1).Value.ToString()
         nonqueryCommand.Parameters("@Col3").Value = row.Cells(2).Value.ToString()

         nonqueryCommand.ExecuteNonQuery()
         

         End If
         Next



       Catch ex As OleDbException
         ' Display error
         Console.WriteLine("Error: " & ex.ToString())
       Finally
         'Close Connection
         thisConnection.Close()

Answer
Hi

You do a check before pass the parameter value should solve your problem.


If row.Cells(0).Value.ToString IsNot Nothing Then
   nonqueryCommand.Parameters("@Col1").Value = row.Cells(0).Value.ToString()
else
   nonqueryCommand.Parameters("@Col1").Value = "0"
end if

Thanks

-Srini

C#

All Answers


Answers by Expert:


Ask Experts

Volunteer


Srini Nagarajan

Expertise

can answer any kind of questions in ASP.NET, C#, VB.NET, ASP, SharePoint 2007, Coldfusion, Powerbuilder 7.00 / 8.00, JAVA servlets, MS SQL 2000 / MSSQL7, Sybase

Experience

Contact me if you need any custom development on ASP.NET, ASP, Coldfusion, Powerbuilder

©2016 About.com. All rights reserved.