簡體   English   中英

Datagridview單元格選定的值插入到sqlserver

[英]Datagridview Cell selected value insert into sqlserver

我有一個帶有datagridview工具的表單,所以我從第一個表單datagridview獲取其他表單datagridview的數據,並從第一個表單datagridview將數據插入sqlserver數據庫。 第一個表格datagridview列名是ItemName,數量,金額等,從其他表格datagridview獲取現在我想從第一個datagridview行插入Itemcode列的Itemcode但我無法做到這一點。

 private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
    {

        if (ActiveControl == dataGridView1 && dataGridView1.CurrentCell == dataGridView1.CurrentRow.Cells[0]) // datagridview first cell enter event
        {
            ItemList fc = new ItemList() { OwnerForm = this }; 
            fc.ShowDialog(this);
            dataGridView1.CurrentRow.Cells[0].Value = ItemName;
            dataGridView1.CurrentRow.Cells[4].Value = Item_MRP;
            dataGridView1.CurrentRow.Cells[5].Value = Item_Purchase;

               }
    }
     private void button1_Click(object sender, EventArgs e)
    {
        try { 
        SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=mateenwin;User ID=sa;Password=123");
        conn.Open();
        SqlCommand commandd = new SqlCommand("SELECT MAX(Pur_Invoice_No)+1  FROM purchase", conn);
        int InvoiceNo = Convert.ToInt32(commandd.ExecuteScalar());

        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            if (row.IsNewRow) continue;

            SqlConnection con = new SqlConnection("Data Source=.; Initial Catalog=mateenwin; User id=sa; password=123");
            SqlCommand command = new SqlCommand("Insert into purchase (Pur_Invoice_No,Pur_Payment_Type_ID, Supplier_Bill_No,Supplier_ID,Item_Code,Pur_Item_Batch_No,Item_Batch_Expiry,Pur_Item_PackQuantity,Purchase_Pack_Price,Discount_Percentage,Extra_Discount_Percentage,MRP_Final,Login_ID,Pur_Entry_Date) values ('" + InvoiceNo + "','" + this.comboBox1.SelectedValue + "','" + this.textBox2.Text + "','" + this.comboBox2.SelectedValue + "','" + row.Cells[0].Value + "','" + row.Cells[1].Value + "','" + row.Cells[2].Value + "','" + row.Cells[3].Value + "','" + row.Cells[5].Value + "','" + row.Cells[6].Value + "','" + row.Cells[7].Value + "','" + row.Cells[4].Value + "','" + this.comboBox3.Text + "',  GetDate())", con);
            con.Open();


            using (con)
            {

                command.ExecuteNonQuery();
            }

        }
            MessageBox.Show("Invoice successfully Saved");
            dataGridView1.Focus();
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

而不是像現在那樣輸入變量。 將它們添加為像這樣的參數會更好更安全

command.Parameters.Add("@parameterName", SqlDbType.CharOrWhateverType).Value = variable;

並像這樣修改您的SqlQuery

"Insert into purchase (Pur_Invoice_No) values (@parameterName)"

如果再次失敗,請提供有關您獲得的例外情況的信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM