简体   繁体   English

使用C#将ListBox项目插入.accdb

[英]Inserting ListBox Items to .accdb with C#

I'm confused any help would be great. 我很困惑,任何帮助都会很棒。

I have a listbox with employee names that are read in from a .accdb. 我有一个列表框,其中包含从.accdb读取的员工姓名。 That part works fine. 那部分工作正常。 Then I make changes to the listbox items in the windowsform. 然后,我对Windows窗体中的列表框项进行更改。 Now I want to insert the changes I've made in the listbox back to the .accdb. 现在,我要将在列表框中所做的更改重新插入.accdb。 My problem is when I click the save button it is only adding the first item in my listbox instead of each one. 我的问题是,当我单击“保存”按钮时,它仅添加了列表框中的第一项,而不是每个项。 I'm not sure why it's only adding the one item instead of them all. 我不确定为什么只添加一项而不是全部添加。 Thanks a lot if you can help! 非常感谢您的帮助!

    private void SaveButton_Click(object sender, EventArgs e)
    {
        string connectString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=WorkReportDatabase.accdb;Persist Security Info=False;";

        OleDbConnection connectEmployee = new OleDbConnection();
        connectEmployee.ConnectionString = connectString;
        connectEmployee.Open();

        OleDbCommand commandEmployee = new OleDbCommand();
        commandEmployee.Connection = connectEmployee;
        commandEmployee.CommandText = "INSERT INTO TestTable (TestColumn) VALUES (@TestTable)";

        for(int i = 0; i < EmployeeList.Items.Count; i++)
        {
            string item = EmployeeList.GetItemText(EmployeeList.Items[i]);

            commandEmployee.Parameters.AddWithValue("@TestTable", item);

            commandEmployee.ExecuteNonQuery();

        }
        connectEmployee.Close();           
    }

Try clearing out the parameters since you keep adding them: 尝试清除参数,因为您不断添加它们:

commandEmployee.Parameters.Clear();
commandEmployee.Parameters.AddWithValue("@TestTable", item);

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

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