gpt4 book ai didi

c# - 如何将新添加的数据行从datagridview插入数据库?

转载 作者:搜寻专家 更新时间:2023-10-30 19:49:08 28 4
gpt4 key购买 nike

我有一个 datagridview,表中有一些数据。datagridview 允许用户输入新的数据行

问题在这里:

我想知道如何在不添加将被复制的现有数据的情况下将新插入的数据行(无论添加了多少行)放入数据库。

有人吗?

编辑:我正在使用 sql 数据库,这是我的数据 GridView 。

enter image description here

显示的数据已经在数据库中,现在,如果用户向 datagridview 中插入新的多行数据怎么办?我应该输入什么代码?

我的代码如下:

private void button1_Click(object sender, EventArgs e)
{
con = new System.Data.SqlClient.SqlConnection();
con.ConnectionString = "Data Source=tcp:SHEN-PC,49172\\SQLEXPRESS;Initial Catalog=LSEStock;Integrated Security=True";
con.Open();
SqlDataAdapter da = new SqlDataAdapter();

for (int i = 0; i<dataGridView1.Rows.Count; i++ )
{

String insertData = "INSERT INTO CostList(SupplierName, CostPrice, PartsID) VALUES (@SupplierName, @CostPrice, @PartsID)" ;
SqlCommand cmd = new SqlCommand(insertData, con);
cmd.Parameters.AddWithValue("@SupplierName", dataGridView1.Rows[i].Cells[0].Value);
cmd.Parameters.AddWithValue("@CostPrice", dataGridView1.Rows[i].Cells[1].Value);
cmd.Parameters.AddWithValue("@PartsID", textBox1.Text);
da.InsertCommand = cmd;
cmd.ExecuteNonQuery();
}

con.Close();

最佳答案

这是我的插入、取消和删除语句:

    protected void gv_RowCommand(object sender, GridViewCommandEventArgs e)
{

if (e.CommandName == "Insert") //- this is needed to explain that the INSERT command will only work when INSERT is clicked
{
gv.DataBind();

DataTable d = dbcon.GetDataTable("SELECT * FROM CIS.CIS_TRANS ORDER BY ID DESC", "ProjectCISConnectionString");

string transCode = "", fundCode = "", BSA_CD = "", DP_TYPE = "";

if (d.Rows.Count > 0)
{
transCode = d.Rows[0]["TRANS_CD"].ToString();
fundCode = d.Rows[0]["FUND_CD"].ToString();
BSA_CD = d.Rows[0]["BSA_CD"].ToString();
DP_TYPE = d.Rows[0]["DP_TYPE"].ToString();

if (transCode.Trim().Length > 0)
{
dbcon.Execute("INSERT INTO CIS.CIS_TRANS (ID,TRANS_CD) VALUES(CIS.S_CIS_TRANS.nextval,'')", "ProjectCISConnectionString");

gv.DataBind();
}
}
gv.EditIndex = gv.Rows.Count - 1;

}
else if (e.CommandName == "Cancel")
{
DataTable d = dbcon.GetDataTable("SELECT * FROM CIS.CIS_TRANS ORDER BY ID DESC", "ProjectCISConnectionString");

string transCode = "";

if (d.Rows.Count > 0)
{
transCode = d.Rows[0]["TRANS_CD"].ToString();

if (transCode.Trim().Length == 0)
{
dbcon.Execute(string.Format("DELETE CIS.CIS_TRANS WHERE ID = '{0}'", d.Rows[0]["ID"]), "ProjectCISConnectionString");

gv.DataBind();
}
}

关于c# - 如何将新添加的数据行从datagridview插入数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11856695/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com