输入字符串的格式不正确

时间:2013-11-25 19:54:37

标签: c# .net

string CommandText = "insert into dbo.printing_list(batch_code,bill_no,date,sr_no,gross_wt,core_wt,nett_wt,c_id,category) values('" + 
                      comboBox2.Text.ToString() + 
                      "','" + textBox1.Text.ToString() + "','" + 
                      dateTimePicker1.Value + "','" +
                      dataGridView1.Rows[i].Cells[1].Value + "','" +
                      Convert.ToDecimal(dataGridView1.Rows[i].Cells[2].Value) + 
                      "','" + Convert.ToDecimal(label2.Text.ToString()) + "','" + 
                      dataGridView1.Rows[i].Cells[3].Value + "','" + g + "','" +
                      comboBox1.Text.ToString() + "')";

1 个答案:

答案 0 :(得分:4)

您必须使用参数化查询而不是字符串连接。

使用以下方法修改您的c#代码:

string connString = "Your connection string here";
using(SqlConnection cn = new SqlConnection(connString))
{
  cn.Open();
  string query = "insert into dbo.printing_list(batch_code,bill_no,date,sr_no,gross_wt,core_wt,nett_wt,c_id,category) values(@batch_code,@bill_no,@date ,@sr_no,@gross_wt,@core_wt,@nett_wt,@c_id,@category)";

  SqlCommand cmd = new SqlCommand(query , cn);
  cmd.Parameters.Add(new SqlParameter(@batch_code , cast_value_retrieved_from_your_control));
  cmd.Parameters.Add(new SqlParameter(@bill_no , cast_value_retrieved_from_your_control));
  cmd.Parameters.Add(new SqlParameter(@date , cast_value_retrieved_from_your_control));
  cmd.Parameters.Add(new SqlParameter(@sr_no , cast_value_retrieved_from_your_control));
  cmd.Parameters.Add(new SqlParameter(@gross_wt , cast_value_retrieved_from_your_control));
  cmd.Parameters.Add(new SqlParameter(@core_wt , cast_value_retrieved_from_your_control));
  cmd.Parameters.Add(new SqlParameter(@nett_wt , cast_value_retrieved_from_your_control));
  cmd.Parameters.Add(new SqlParameter(@c_id , cast_value_retrieved_from_your_control));
  cmd.Parameters.Add(new SqlParameter(@category , cast_value_retrieved_from_your_control));
  int retval = cmd.ExecuteNonQuery();
  if(retval > 0)
  {
      //A Label you can keep your page for showing message - named as "Label1"
       Label1.Text = "Inserted Successfully";
  }
}