我有这个基本的WinForms应用程序用户界面:
当我点击“Gem”按钮时,我想将数据添加到DataGridView和sql表中。我有以下代码:
private void Form2_Load(object sender, EventArgs e)
{
try
{
con = new SqlConnection();
con.ConnectionString = @"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Produkt.mdf;Integrated Security=True";
con.Open();
//adap = new SqlDataAdapter("select SN, FName as 'Navn', MName as 'Vare nr', LName as 'Antal', Age from Produkt", con);
string sql = "SELECT Navn, Varenr, Antal, Enhed, Priseksklmoms, Konto FROM ProduktTable";
adap = new SqlDataAdapter(sql, con);
ds = new System.Data.DataSet();
adap.Fill(ds, "ProduktTable");
dataGridView1.DataSource = ds.Tables["ProduktTable"];
}
catch (Exception ex)
{
MessageBox.Show("Error\n" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void button1_Click(object sender, EventArgs e)
{
string navn = textBox2.Text;
int varenr = int.Parse(textBox3.Text);
float antal = (float)Convert.ToDouble(textBox4.Text);
string enhed = textBox5.Text;
string konto = comboBox2.Text;
float pris = (float)Convert.ToDouble(textBox6.Text);
dataGridView1.Rows[0].Cells[0].Value = navn;
dataGridView1.Rows[0].Cells[1].Value = varenr;
string StrQuery;
try
{
SqlCommand comm = new SqlCommand();
comm.Connection = con;
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
StrQuery = @"INSERT INTO ProduktTable VALUES ('"
+ dataGridView1.Rows[i].Cells[0].Value + "',' "
+ dataGridView1.Rows[i].Cells[1].Value + "');";
comm.CommandText = StrQuery;
comm.ExecuteNonQuery();
}
}
catch (Exception ex)
{
MessageBox.Show("Error\n" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
这只是一个例子,目的是在DataGridView和sql中存储字符串“navn”和整数“Varenr”。当我运行应用程序并单击按钮时,会出现以下错误:
我的ProduktTable表的列名与dataGridView的列名完全相同。
提前致谢
答案 0 :(得分:1)
在insert语句中明确设置列名...
StrQuery = @"INSERT INTO ProduktTable (Navn, Varenr) VALUES ('"
+ dataGridView1.Rows[i].Cells[0].Value + "',' "
+ dataGridView1.Rows[i].Cells[1].Value + "');";