尝试将datagridview插入SQL Server数据库

时间:2018-01-16 14:56:47

标签: c# sql-server

我正在尝试将我的datagridview数据导入我的SQL Server数据库,但是我收到了错误

  

无法将参数值从DataGridView TextVoxCell转换为变量类型

有人可以指导我走正确的道路吗?

for (int r = 1; r < dataGridView1.Rows.Count; r++)
{
    for (int c = 1; c < dataGridView1.Columns.Count; c++)
    {
        try
        {
            SqlConnection con = new SqlConnection(constring);

            SqlCommand query = new SqlCommand("INSERT into RosterTest (EmployeeID, Date, ShiftType) Values (@EmployeeID,@Date,@ShiftType", con);

            query.Parameters.Add("@EmployeeID", SqlDbType.Int).Value = dataGridView1.Columns[c].HeaderText;
            query.Parameters.Add("@Date", SqlDbType.Date).Value = dataGridView1.Rows[r].Cells[0];
            query.Parameters.Add("ShiftType", SqlDbType.NVarChar).Value = dataGridView1.Rows[r].Cells[c];

            con.Open();
            query.ExecuteNonQuery();
        }
    }
}

enter image description here

2 个答案:

答案 0 :(得分:1)

尝试将Value添加到您的单元格,它是包含信息的属性。

query.Parameters.Add("@Date", SqlDbType.Date).Value = dataGridView1.Rows[r].Cells[0].Value;

答案 1 :(得分:0)

为我的查询参数添加了.Value。插入现在有效!

for (int r = 0; r < dataGridView1.Rows.Count; r++)
            {
                for (int c = 1; c < dataGridView1.Columns.Count; c++)
                {
                    try
                    {
                        SqlConnection con = new SqlConnection(constring);
                        SqlCommand query = new SqlCommand("INSERT into RosterTest (EmployeeID, Date, ShiftID) Values (@EmployeeID,@Date,@ShiftID)", con);
                        query.Parameters.Add("@EmployeeID", SqlDbType.Int).Value = dataGridView1.Columns[c].HeaderText;
                        query.Parameters.Add("@Date", SqlDbType.Date).Value = dataGridView1.Rows[r].Cells[0].Value;
                        query.Parameters.Add("@ShiftID", SqlDbType.NVarChar).Value = dataGridView1.Rows[r].Cells[c].Value;
                        con.Open();
                        query.ExecuteNonQuery();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }

            }