如何使用此代码将数据从DataGridView1保存到SQL?

时间:2013-09-12 06:45:31

标签: c# sql datagridview

我想使用包含for循环的代码将数据保存到SQL但我发现此问题“输入字符串的格式不正确。”。

private void btnDataSave_Click(object sender, EventArgs e)
    {
        using (SqlConnection CN = new SqlConnection(txtConString.Text))
        {
            using (SqlCommand command = new SqlCommand())
            {
                command.Connection = CN;
                command.CommandText = "insert into MRRDataStore(id, unit, qty, desc, remark) values(@id, @unit, @qty, @desc, @remark)";
                CN.Open();
                foreach (DataGridViewRow row in dataGridView1.Rows)
                {
                    if (!row.IsNewRow)
                    {
                        int id;
                        string unit;
                        string qty;
                        string desc;
                        string remark;

                        for (int i = 0; i <= dataGridView1.Rows.Count - 1; i++)
                        {
                            id = int.Parse(dataGridView1.Rows[i].Cells["Id"].Value.ToString());
                            unit = dataGridView1.Rows[i].Cells["Unit"].Value.ToString();
                            qty = dataGridView1.Rows[i].Cells["Qty"].Value.ToString();
                            desc = dataGridView1.Rows[i].Cells["ItemDesc"].Value.ToString();
                            remark = dataGridView1.Rows[i].Cells["Remarks"].Value.ToString();
                        }
                    }
                }
            }
        }
    }

0 个答案:

没有答案