在数据库中插入datagridview的值
本文关键字:datagridview 的值 插入 数据库 | 更新日期: 2023-09-27 18:25:00
我创建了一个绑定到数据表的数据网格视图。如何通过单击1次按钮将数据表中的所有内容添加到数据库中?例如:我在数据表中插入了5个值。如何一次插入所有5个数据表?
您可以这样做:
string ConnString= "Data Source=.'SQLEXPRESS;Initial Catalog=test;Integrated Security=True;Pooling=False";
private void button1_Click(object sender, EventArgs e)
{
for(int i=0; i< dataGridView1.Rows.Count;i++)
{
string StrQuery= @"INSERT INTO tableName VALUES (" + dataGridView1.Rows[i].Cells["ColumnName"].Value +", " + dataGridView1.Rows[i].Cells["ColumnName"].Value +");";
try
{
using (SqlConnection conn = new SqlConnection(ConnString))
{
using (SqlCommand comm = new SqlCommand(StrQuery, conn))
{
conn.Open();
comm.ExecuteNonQuery();
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
ConnectionString,您可以从DB的属性中获取它,当您想要插入非数字的值时,也可以在命令中放入"。。。