如何将数据网格中的所有列添加到SQL Server 2008数据库

时间:2013-05-12 08:56:48

标签: c# sql sql-server-2008

我正在使用datagridview并向其中添加了列...因此我使用文本框将数据添加到datagridview ..这是客户想要购买的产品列表..第一列是CustCode, ItemCode, DateQuantity ..这些是4列,我添加了很多行..

假设我在datagridview中插入了5行....我现在想将datagridview中的所有数据添加到SQL Server 2008数据库....有人可以编写整个代码吗?我真的很困惑,这个代码我似乎不起作用...给出一个错误..null参数

SqlConnection con = new System.Data.SqlClient.SqlConnection();
con = new System.Data.SqlClient.SqlConnection();
con.ConnectionString = "Data Source=rex;Initial Catalog=Project DB 1;Integrated Security=True";

con.Open();
SqlDataAdapter da = new SqlDataAdapter();

for (int i = 0; i <= dataGridView1.Rows.Count - 1; i++)
{
    String insertData = "INSERT INTO SalesTable(CustCode,ItemCode,Date,Quantity) " + 
                        "VALUES (@CustCode,@ItemCode,@Date,@Quantity)";

    SqlCommand cmd = new SqlCommand(insertData, con);
    cmd.Parameters.AddWithValue("@CustCode", dataGridView1.Rows[i].Cells[0].Value);
    cmd.Parameters.AddWithValue("@ItemCode", dataGridView1.Rows[i].Cells[1].Value);
    cmd.Parameters.AddWithValue("@Date", dataGridView1.Rows[i].Cells[2].Value);
    cmd.Parameters.AddWithValue("@Quantity", dataGridView1.Rows[i].Cells[3].Value);

    da.InsertCommand = cmd;
    cmd.ExecuteNonQuery();
}
con.Close();

1 个答案:

答案 0 :(得分:1)

如果我理解你的问题,那么你有一个或多个不包含值的网格单元格,因此你得到一个空参数 - 要在数据库中插入一个你需要传递的空值(作为参数)DBNull.Value

因此您的代码可以重写为

using(SqlConnection con = new System.Data.SqlClient.SqlConnection("Data Source=rex;Initial Catalog=Project DB 1;Integrated Security=True"))
{
    con.Open();
    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        if(!row.IsNewRow)
        {
            String insertData = "INSERT INTO SalesTable(CustCode,ItemCode,Date,Quantity) " + 
                                "VALUES (@CustCode,@ItemCode,@Date,@Quantity)";

            SqlCommand cmd = new SqlCommand(insertData, con);
            cmd.Parameters.AddWithValue("@CustCode", row.Cells[0].Value ?? DbNull.Value);
            cmd.Parameters.AddWithValue("@ItemCode", row.Cells[1].Value ?? DBNull.Value);
            cmd.Parameters.AddWithValue("@Date", row.Cells[2].Value ?? DBNull.Value);
            cmd.Parameters.AddWithValue("@Quantity", row.Cells[3].Value ?? DBNUll.Value);
            cmd.ExecuteNonQuery();
        }
    }
}

我使用C# Null Coalescing operator来测试你的一个单元格的值是否为空 我还删除了无用的DataAdapter并修复了连接的创建,初始化和处理

另请参阅DataGridViewRow中的IsNewRow Property