且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在数据库中插入datagridview的值

更新时间:2023-02-08 17:30:31

你可以这样做:

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的属性,当你想插入不是数字的值时,也在命令中放上'...

the ConnectionString you can get it from the property of you DB, also put " ' " in the Command when you want to insert value which is not number...