我在一个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.
}

最佳答案

请注意,使用直接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();

    }

09-26 20:36
查看更多