简体   繁体   English

在“库存”列中使用 +1 或 -1 更新 Excel 工作表

[英]Updating Excel sheet with +1 or -1 in column 'stock'

https://imgur.com/a/OKZPMYl I am loading a excel file into a datagridview with this code https://imgur.com/a/OKZPMYl我正在使用此代码将 excel 文件加载到 datagridview 中

private void Loadexcel_Click(object sender, EventArgs e)
    {
        OpenFileDialog importexcel = new OpenFileDialog();
        importexcel.Filter = "Excel files | *.xlsx";
        if (importexcel.ShowDialog() == DialogResult.OK)
            filetextBox.Text = importexcel.FileName;

        String connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filetextBox.Text + ";Extended Properties=Excel 12.0;";
        OleDbConnection conn = new OleDbConnection(connStr);
        string strSQL = "SELECT * FROM [Sheet1$]";
        OleDbCommand cmd = new OleDbCommand(strSQL, conn);
        DataTable dT = new DataTable();
        
        conn.Open();
        try
        {
            OleDbDataReader dR = cmd.ExecuteReader();
            dT.Load(dR);
            excelviewgrid.DataSource = dT;
        }
        catch (Exception ex)

        {
            MessageBox.Show(ex.Message);
        }

        finally
        {
            conn.Close();
            NewOrder.Enabled = true;
        }
    
        
    }

i am adding items to my listbox with a textboxinput from the user that should match the Material number which adds the information from material description column and some extra hardcoded text.我正在使用来自用户的文本框输入将项目添加到我的列表框中,该文本框输入应该与添加来自材料描述列的信息和一些额外硬编码文本的材料编号相匹配。 and also loops the input to the amount input in the combobox.并且还将输入循环到 combobox 中的输入量。 so far this all works.到目前为止,这一切都有效。

private void textBoxInput_KeyUp(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
        {
            string strCurrentString = textBoxInput.Text.Trim().ToString();

            if (strCurrentString != "")
            {
                if (radioButtonPick.Checked == true && radioButtonNew.Checked == true)
                {
                    foreach (DataGridViewRow row in excelviewgrid.Rows)
                    {
                        if (textBoxInput.Text == row.Cells["Material"].Value.ToString())
                        {
                            int value = Convert.ToInt32(comboBoxmultiply.Text);
                            for (int i = 0; i < value; i++)
                            {
                                listBoxinput.Items.Add(textBoxInput.Text + " | " + row.Cells["Material Description"].Value + " (-1 New Pick)");
                            }
                            comboBoxmultiply.SelectedIndex = 0;
                            textBoxInput.Clear();

                        }

                    }

                }
            }

but now i want to make it that for each item on the listbox https://imgur.com/a/soeENXs it updates the stock collumn by +1 or -1 depending on pick or receive(this is done with using the right event trigger(if radiobuttonxxx == true) and give an error if going below 0但现在我想让它对于列表框https://imgur.com/a/soeENXs上的每个项目,它会根据选择或接收将股票列更新 +1 或 -1(这是通过使用正确的事件完成的触发(如果 radiobuttonxxx == true),如果低于 0 则给出错误

 private void buttontest_Click(object sender, EventArgs e)
    {
        String connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filetextBox.Text + ";Extended Properties=Excel 12.0;";
        OleDbConnection conn = new OleDbConnection(connStr);

        conn.Open();
        OleDbCommand ojbCmdSelect = new OleDbCommand("UPDATE [sheet1$] set [Stock] = [Stock] + 1 where [Material] = 114-6776");
        ojbCmdSelect.ExecuteNonQuery();
        conn.Close();
    }

FIXED look further I tried this code with a test button and just the material from one item(this needs to be changed to every item on the listbox) on the excel list. FIXED 进一步看我用一个测试按钮尝试了这段代码,只是 excel 列表中的一个项目(这需要更改为列表框中的每个项目)的材料。

but it throws me a error "System.InvalidOperationException: 'ExecuteNonQuery: Connection property was not initialized.'"但它给我一个错误“System.InvalidOperationException:'ExecuteNonQuery:连接属性未初始化。'”

EDIT: the connection issue seems to be fixed with this code EDIT:2 massively improved and corrected by Cetin Basoz (look below)编辑:连接问题似乎已通过此代码修复编辑:2 由 Cetin Basoz 进行了大规模改进和纠正(如下所示)

conn.Open();
        string strSQL = "UPDATE [sheet1$] set Stock = stock+1 where Material = '114-6776'";
        OleDbCommand ojbCmdSelect = new OleDbCommand(strSQL,conn);
        ojbCmdSelect.ExecuteNonQuery();
        conn.Close();

now i need to figure out how i can make the "where material = listboxitems" EDIT:3 also provided by Cetin Basoz(look below)现在我需要弄清楚如何制作“where material = listboxitems”编辑:3 也由 Cetin Basoz 提供(如下所示)

I am new to coding so no experience.我是编码新手,所以没有经验。

As the message says, ojbCmdSelect needs a connection and you didn't set it.正如消息所说,ojbCmdSelect 需要一个连接,而您没有设置它。 Also if you pass that, there is another error in the OleDbCommand text itself.此外,如果您通过它,OleDbCommand 文本本身还会出现另一个错误。 You should use parameters and you could do the update single or in a loop.您应该使用参数,并且可以单独或循环进行更新。 ie: IE:

private void buttontest_Click(object sender, EventArgs e)
{
    String connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filetextBox.Text + ";Extended Properties=Excel 12.0;";
    using (OleDbConnection conn = new OleDbConnection(connStr))
    using (OleDbCommand ojbCmdSelect = new OleDbCommand("UPDATE [sheet1$] set [Stock] = [Stock] + 1 where [Material] = @material", conn))
    { 
        ojbCmdSelect.Parameters.Add("@material", OleDbType.VarChar);
        
    
        conn.Open();
        // this part could be in a loop
        // for ... {
        ojbCmdSelect.Parameters["@material"].Value = "114-6776";
        ojbCmdSelect.ExecuteNonQuery();
        // }
        conn.Close();
    }
}

EDIT: As per the listbox.items, you are adding items to listbox with their code appended extra space |编辑:根据 listbox.items,您正在将项目添加到列表框中,其代码附加了额外的空间 | and then description.然后描述。 You first need to get the code per listbox item:您首先需要获取每个列表框项的代码:

private void buttontest_Click(object sender, EventArgs e)
{
    String connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filetextBox.Text + ";Extended Properties=Excel 12.0;";
    using (OleDbConnection conn = new OleDbConnection(connStr))
    using (OleDbCommand ojbCmdSelect = new OleDbCommand("UPDATE [sheet1$] set [Stock] = [Stock] + 1 where [Material] = @material", conn))
    { 
        ojbCmdSelect.Parameters.Add("@material", OleDbType.VarChar);
        
    
        conn.Open();
        foreach (string item in listBoxinput.Items)
        {
            var itemcode = item.Split('|')[0].Trim();
            ojbCmdSelect.Parameters["@material"].Value = itemcode;
            ojbCmdSelect.ExecuteNonQuery();

        }
        conn.Close();
    }
}

PS: In a real world application, instead of having such items in a listbox, you would want to bind it to an object where it has Id and the display text at least. PS:在现实世界的应用程序中,您可能希望将其绑定到至少具有 Id 和显示文本的 object ,而不是在列表框中包含此类项目。 Splitting from a long string to get the Id is not feasible at all times.从一个长字符串中拆分来获取 Id 在任何时候都是不可行的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM