inserting every row in grideview

时间:2016-04-25 09:36:30

标签: c# sql-server

I am trying to insert every row in the GridView into a table on a click of button. My problem with the code below is that the data was inserted but i cant handle the exception i used this code

string constring = @"Data Source=WINCTRL-RDJN6O6;Initial Catalog=Care_AlexDemo;Integrated Security=True";
    using (SqlConnection con = new SqlConnection(constring))
    {
        using (SqlCommand cmd = new SqlCommand("INSERT INTO TeseI VALUES(@Emp_name, @Emp_number)", con))
        {
            cmd.Parameters.AddWithValue("@Emp_name", row.Cells["Emp_name"].Value);
            cmd.Parameters.AddWithValue("@Emp_number", row.Cells["Emp_number"].Value);
            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
        }
    }
}
MessageBox.Show("Records inserted.");

1 个答案:

答案 0 :(得分:0)

我不明白变量'row'是什么,我想它意味着DataGridView.Rows中的每一行,所以你试图逐行向数据库插入行?通常我想用'INSERT INTO [TABLE_NAME] SELECT ...'语句插入所有行一次。所以代码可能是这样的:

StringBuilder strsql = new StringBuilder("INSERT INTO TeseI ");
foreach (var row in DataGridView.Rows)
{
    strsql.AppendFormat(" SELECT '{0}', '{1}' UNION ALL ", row.Cells["Emp_name"].Value, row.Cells["Emp_number"].Value);
}
// remove the last 'UNION ALL '
strsql.Remove(strsql.Length - 10, 10);
string constring = @"Data Source=WINCTRL-RDJN6O6;Initial Catalog=Care_AlexDemo;Integrated Security=True";
using (SqlConnection con = new SqlConnection(constring))
{
    using (SqlCommand cmd = new SqlCommand(strsql.ToString(), con))
    {
        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();
    }
}
MessageBox.Show("Records inserted.");
顺便说一句,我认为我们可以删除'con.Open()'和'con.Close()'方法的显式调用,因为我们使用'using'语句

我只是按照我做的方式,因为你没有显示异常消息。无论如何,
希望这可以帮助