我想在数据表中插入数据网格视图中输入的值。 我试过代码..
private void btnSave_Click(object sender, EventArgs e)
{
billNO++;
if (con.State == ConnectionState.Open) { con.Close(); }
con.Open();
string s = "CREATE TABLE [" + "" + combCustomerName.Text + "] (SlNO int Not Null , ItemDesc varchar(100) , ItemDetails varchar(100) , UMO varchar(10) , Quntity numeric(10,3) , Rate numeric(10,2) , Amount numeric(10,2) , GrossTot numeric(10,2) , Discount numeric(7,2) , Taxpc numeric(5,2) , TaxAmt numeric(5,2) , OtherAmt numeric(7,2) , NetAmt numeric(10,2))";
SqlCommand cmd = new SqlCommand(s, con);
cmd.ExecuteNonQuery();
//string insert=null;
SqlCommand inscmd = new SqlCommand();
for (int i = 0; i < datagridItemEntry.Rows.Count; i++)
{
inscmd.CommandText = "INSERT INTO [" + "" + combCustomerName.Text + "] VALUES(" + datagridItemEntry.Rows[i].Cells[0].Value.ToString() + "','" + datagridItemEntry.Rows[i].Cells[1].Value.ToString() + "','" + datagridItemEntry.Rows[i].Cells[2].Value.ToString() + "','" + datagridItemEntry.Rows[i].Cells[3].Value.ToString() + "','" + datagridItemEntry.Rows[i].Cells[4].Value.ToString() + "','" + datagridItemEntry.Rows[i].Cells[5].Value.ToString() + "','" + datagridItemEntry.Rows[i].Cells[6].Value.ToString() + "','" + datagridItemEntry.Rows[i].Cells[7].Value.ToString() + "','" + datagridItemEntry.Rows[i].Cells[8].Value.ToString() + "','" + datagridItemEntry.Rows[i].Cells[9].Value.ToString() + "','" + datagridItemEntry.Rows[i].Cells[10].Value.ToString() + "','" + datagridItemEntry.Rows[i].Cells[11].Value.ToString() + "','" + datagridItemEntry.Rows[i].Cells[12].Value.ToString() + "','" + datagridItemEntry.Rows[i].Cells[13].Value.ToString() + "')";
}
if (inscmd.ExecuteNonQuery() >= 1)
{
MessageBox.Show("Done!");
}
con.Close();
}
正在创建表格.. 插入时,我的索引超出范围我得到例外。 帮助我。
答案 0 :(得分:1)
只需复制在执行第一个查询后粘贴此代码。
for (int i = 0; i < datagridItemEntry.Rows.Count; i++)
{
string query1 = "insert into "+combCustomerName.Text+" values(" + gvSalesInv.Rows[i].Cells[0].Value + "," + gvSalesInv.Rows[i].Cells[1].Value + "," + gvSalesInv.Rows[i].Cells[2].Value + "," + gvSalesInv.Rows[i].Cells[3].Value + "," + gvSalesInv.Rows[i].Cells[4].Value + "," + gvSalesInv.Rows[i].Cells[5].Value + "," + gvSalesInv.Rows[i].Cells[6].Value + "," + gvSalesInv.Rows[i].Cells[7].Value + "," + gvSalesInv.Rows[i].Cells[8].Value + "," + gvSalesInv.Rows[i].Cells[9].Value + "," + gvSalesInv.Rows[i].Cells[10].Value + "," + gvSalesInv.Rows[i].Cells[11].Value + ")";
SqlCommand cmd1 = new SqlCommand(query1, con);
cmd1.ExecuteNonQuery();
}