在数据库中插入datagridview的值

在数据库中插入datagridview的值

本文介绍了在数据库中插入datagridview的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个datagridview,它绑定到一个datatable。如何使用1 buttonclick将数据库中的所有内容添加到数据库?例如:我已经在我的数据表中插入了5个值。如何一次插入所有5个datatable?

I've created a datagridview which is binded to a datatable. How would I add all of the contents in my datatable to the database with 1 buttonclick? for ex: I have inserted 5 values in my datatable. How would I insert all of the 5 datatable at once?

推荐答案

你可以这样做:

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...

这篇关于在数据库中插入datagridview的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 01:59