【问题标题】:Inserting values from datagridview into SQL Server database in C#在 C# 中将 datagridview 中的值插入 SQL Server 数据库
【发布时间】:2013-06-16 09:07:57
【问题描述】:

我在 SQL Server 数据库中有两个表,productinnvoice

我正在从表 product 中获取选定的数据并将它们显示在 datagridview 中。

现在我想将 datagridview 中的数据存储到表 innvoice。所有这些操作都只需单击一个按钮。

这是我的代码:

private void button5_Click_2(object sender, EventArgs e) //add produt
{
        SqlConnection con = new SqlConnection(@"Persist Security Info=False;User ID=usait;password=123;Initial Catalog=givenget;Data Source=RXN-PC\ROSHAAN");
        con.Open();
        SqlDataAdapter da = new SqlDataAdapter("SELECT product.p_name,product.p_category, product.sale_price FROM product where p_code='" + textBox16.Text + "'", con);
        DataTable dt = new DataTable();

        da.Fill(dt);
        dataGridView3.DataSource = dt;

        // here I want to insert values from datagridview3 to table innvoice.
}

【问题讨论】:

  • 您需要插入查询。看在上帝的份上,请搜索 SO..
  • 这是Invoice - 只有一个“n”。而且您应该停止将您的 SQL 语句连接在一起 - 这只是在邀请黑客利用您的 SQL 注入弱点!使用参数化查询 - 总是。
  • 您可以从 dt 插入记录,而不是 dataGridView。
  • 我不确定您的两个表的架构结构是什么样的,但您最好使用产品表中的 Id 作为发票表中的外键。这样,发票表就只有发票的特定信息,而您不会到处重复信息。

标签: c# sql-server database datagrid


【解决方案1】:

请注意。使用直接 SQL 查询不是一个好习惯。

希望这会对你有所帮助。

 private void button5_Click_2(object sender, EventArgs e) //add produt
    {
            SqlConnection con = new SqlConnection(@"Persist Security Info=False;User ID=usait;password=123;Initial Catalog=givenget;Data Source=RXN-PC\ROSHAAN");
            Dataset ds=new Dataset();
            con.Open();
            SqlDataAdapter da = new SqlDataAdapter("SELECT product.p_name,product.p_category, product.sale_price FROM product where p_code='" + textBox16.Text + "'", con);
            da.Fill(ds);
            dataGridView3.DataSource = ds;

            //Code to insert values into Invoice
            for( i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
               sqlcommand cmd=new sqlcommand();
               cmd=new sqlcommand("insert into invoice(pname,pcategory,psaleprice) values('"+ds.Tables[0].Rows[i]["product.p_name"].ToString()+"','"+ds.Tables[0].Rows[i]["product.p_category"].ToString()+"','"+ds.Tables[0].Rows[i]["product.sale_price"].ToString()+"')",con);
               cmd.executeNonquery();
            }
            con.close();

    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多