0

Currently I'm developing a program for windows CE, that has a connection with Sql Server. I was able to get the data but whenever I was trying to add a data in the database. It always shows SqlException

here is my code (this is just a prototype>


string insert = string.Empty;
string data1 = textBox1.ToString(), data2 = textBox2.ToString(); 

string conSTR = "Data Source=<ipAdd>;" //server + "Initial Catalog=test;" database + "User id=testuser;" + "Password=;"; 
SqlConnection conn = new SqlConnection(conSTR);
insert = "Insert into Customers values(@id,@name);"; 
SqlCommand cmd = new SqlCommand(insert, conn); 
cmd.Connection.Open();
cmd.Parameters.Add("@id", textBox1.ToString()); 
cmd.Parameters.Add("@name", textBox2.ToString()); 
cmd.ExecuteNonQuery(); 
cmd.Connection.Close();

Specific Exception

System.Data.SqlClient.SqlException was unhandled
  Message="SqlException"
  Class=16
  LineNumber=1
  Number=8152
  Procedure=""
  Server="LAPTOP-AEUVQN3B"
  Source=".Net SqlClient Data Provider"
  State=13
  StackTrace:
       at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, TdsParserState state)
       at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, TdsParserState state)
       at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning()
       at System.Data.SqlClient.TdsParser.Run(RunBehavior run, SqlCommand cmdHandler, SqlDataReader dataStream)
       at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream)
       at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
       at sqlSample.create.button1_Click(Object sender, EventArgs e)
       at System.Windows.Forms.Control.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnClick(EventArgs e)
       at System.Windows.Forms.ButtonBase.WnProc(WM wm, Int32 wParam, Int32 lParam)
       at System.Windows.Forms.Control._InternalWnProc(WM wm, Int32 wParam, Int32 lParam)
       at Microsoft.AGL.Forms.EVL.EnterMainLoop(IntPtr hwnMain)
       at System.Windows.Forms.Application.Run(Form fm)
       at sqlSample.Program.Main()

Below here is a image of where does the error happens

ErrorImage

1 Answers1

1

textBox1.ToString() probably returns something like "System.Windows.Forms.TextBox, Text: 1".

Use the Text property instead:

cmd.Parameters.Add("@id", textBox1.Text); 
cmd.Parameters.Add("@name", textBox2.Text); 
C.Evenhuis
  • 25,996
  • 2
  • 58
  • 72