简体   繁体   English

列表框错误:设置了DataSource属性时,无法修改项目集合

[英]listbox error: Items collection cannot be modified when the DataSource property is set

I have 2 listboxes in a window form, one on left and one on right. 我有2个窗口形式的列表框,一个在左侧,一个在右侧。 The 1st listbox have some items while the 2nd listbox is empty. 第一个列表框包含一些项目,而第二个列表框为空。 Also there are 2 buttons between the 2 listboxes which used to move item from/to the 1st and 2nd listbox 在两个列表框之间也有2个按钮,用于将项目从第一个和第二个列表框移入/移出

My problem here is that after I bind the data to the 1st listbox (from a database, using DisplayMember and ValueMember) , and I try to move 1 of the item from this 1st listbox to the 2nd listbox and I want that the selected item is also removed from the 1st listbox by: 我的问题是,在将数据绑定到第一个列表框(从数据库,使用DisplayMember和ValueMember)之后,我尝试将项目1从第一个列表框移动到第二个列表框,并且我希望所选的项目是也通过以下方式从第一个列表框中删除:

    private void btnMoveRight_Click(object sender, EventArgs e)
    {
        ADD();

    }

    private void ADD()
    {
        int c = listJobBox.Items.Count - 1;

  ` for(int i= c; i>=0; i--)
        {
        if(listJobBox.GetSelected(i))
        {

        lstAssignedJobs.Items.Add(listJobBox.Items[i]);

            listJobBox.Items.Remove(listJobBox.SelectedItem); ---error line

But the selected item is not removed from the 1st listbox. 但是,所选项目不会从第一个列表框中删除。

it displays error message "Items collection cannot be modified when the DataSource property is set." 它显示错误消息“设置DataSource属性时无法修改项目集合”。

can any one give me the solution to my problem. 任何人都可以给我解决我的问题的方法。

Add a boolean column to your DataTable object, something like IsSelected . 向您的DataTable对象添加一个布尔列,类似于IsSelected

Then instead of binding your listbox1 directly to the table, bind it to a BindingSource. 然后,而不是将listbox1直接绑定到表,而是将其绑定到BindingSource。 Add 2 bindingsources to your form using the designer. 使用设计器将2个绑定源添加到您的表单。 And place this code in your code behind file. 并将此代码放在文件后面的代码中。

public partial class Form1 : Form
{

    public Form1()
    {
        InitializeComponent();
        this.InitializeDataObjects();
    }

    private void InitializeDataObjects()
    {
        this.InitData();
        this.InitBindingSources();
    }

    private void InitData()
    {
        ds = new DataSet();
        var dt = new DataTable("Table1");
        dt.Columns.Add("Name", typeof(string));
        ds.Tables.Add(dt);
    }

    private void InitBindingSources()
    {
        bindingSource1 = new BindingSource();
        bindingSource2 = new BindingSource();

        bindingSource1.DataSource = ds;
        bindingSource1.DataMember = "Table1";
        bindingSource2.DataSource = ds;
        bindingSource2.DataMember = "Table1";

        listBox1.DataSource = bindingSource1;
        listBox1.DisplayMember = "Name";
        listBox2.DataSource = bindingSource2;
        listBox2.DisplayMember = "Name";
    }
}

Then when you load your data, do the following: 然后,在加载数据时,请执行以下操作:

    private void btnLoadAndBind_Click(object sender, EventArgs e)
    {
        this.FetchData(this.ds.Tables["Table1"]);
        this.AddSelectedColumn(this.ds.Tables["Table1"]);

        this.bindingSource1.Filter = "IsSelected = false";
        this.bindingSource2.Filter = "IsSelected = true";
    }

    private void FetchData(DataTable dataTable)
    {
        string CS = "your connectionstring";
        using (SqlConnection con = new SqlConnection(CS))
        {
            try
            {
                SqlDataAdapter da = new SqlDataAdapter();

                con.Open();
                var sqlcmd = new SqlCommand("SELECT Name FROM sometable", con);
                sqlcmd.CommandType = CommandType.Text;
                da.SelectCommand = sqlcmd;
                da.Fill(dataTable);
            }
            catch (Exception ex)
            {
                MessageBox.Show("exception raised");
                throw ex;
            }
        }
    }

    private void AddSelectedColumn(DataTable suppliersDataTable)
    {
        var dc = new DataColumn("IsSelected", typeof(bool));
        suppliersDataTable.Columns.Add(dc);

        foreach (DataRow dr in suppliersDataTable.Rows)
        {
            dr["IsSelected"] = false;
        }
    }    

Now your listboxes are both connected to the same datatable and filtered based on the IsSelected property / column. 现在,您的列表框都连接到相同的数据表,并根据IsSelected属性/列进行过滤。 Just set this column to true or false and it will flip from box to box. 只需将此列设置为true或false,它就会在框之间翻转。 Your eventhandler of a button could look like this: 您的按钮事件处理程序可能如下所示:

public void button_Click(object sender, EventArgs e)
{
    if (this.bindingSource1.Current!= null)
    {
         var dr = ((DataRowView)this.bindingSource1.Current).Row;
         dr["IsSelected"] = true;
     }
}

This works! 这可行!

Things will be become much simpeler if you use a typed dataset. 如果使用类型化的数据集,事情将变得更加简单。 Most of the bindings then can be done in the designer and your code behind will shrink to 20 lines of code.... 然后,大多数绑定都可以在设计器中完成,您后面的代码将缩减为20行代码。

Lets say listbox1 is bound to datatable1 (it could be any other collection type) and listbox2 is bound to datatable2. 可以说listbox1绑定到datatable1(它可以是任何其他集合类型),而listbox2绑定到datatable2。 When you click on move button, remove the selected item from the collection ie datatable1 and add that item to other collection ie datatable2 and re-bind the listbox1 and lisbox2. 当您单击“移动”按钮时,从集合(即datatable1)中删除选定的项目,然后将该项目添加到其他集合(即datatable2)中,然后重新绑定listbox1和lisbox2。

Here is a rough working example: 这是一个粗略的工作示例:

public partial class Form1 : Form
{
    private DataTable _dataSource1;
    private DataTable _dataSource2;
    public Form1()
    {
        InitializeComponent();

        _dataSource1 = GetData1();
        _dataSource2 = GetData2();
        Initialize();
    }



    private void btnMove_Click(object sender, EventArgs e)
    {
        MoveItem();
    }

    void Initialize()
    {
        listBox1.DataSource = _dataSource1;
        listBox1.DisplayMember = "Fruits";
        listBox1.ValueMember = "Fruits";

        listBox2.DataSource = _dataSource2;
        listBox2.DisplayMember = "Fruits";
        listBox2.ValueMember = "Fruits";
    }

    DataTable GetData1()
    {
        var dt = new DataTable();
        dt.Columns.Add("Fruits");
        dt.Rows.Add(new object[] {"Apple"});
        dt.Rows.Add(new object[] { "Orange" });
        dt.Rows.Add(new object[] { "Grapes" });
        return dt;
    }
    DataTable GetData2()
    {
        var dt = new DataTable();
        dt.Columns.Add("Fruits");
        return dt;
    }

    void MoveItem()
    {
        var index = listBox1.SelectedIndex;
        var dataRowToRemove = _dataSource1.Rows[index];
        var listItem = dataRowToRemove[0] as string;
        _dataSource1.Rows.Remove(dataRowToRemove);


        var dataRowToAdd = _dataSource2.NewRow();
        dataRowToAdd[0] = listItem;
        _dataSource2.Rows.Add(dataRowToAdd); 
        Initialize();

    }

}

暂无
暂无

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

相关问题 如何在不同的 colors 中为列表框中的项目着色? 出现异常:设置 DataSource 属性后无法修改 Items 集合 - How to color items in listBox in different colors? getting exception : Items collection cannot be modified when the DataSource property is set C#ListBox:设置DataSource属性时,无法修改Items集合 - C# ListBox : Items collection cannot be modified when the DataSource property is set 例外:设置DataSource属性时,无法修改项集合 - Exception : Items collection cannot be modified when the DataSource property is set 在c#中设置DataSource属性时,无法修改项目集合 - Items collection cannot be modified when the DataSource property is set in c# 设置DataSource属性时,无法修改c#项目集合 - c# Items collection cannot be modified when the DataSource property is set 设置DataSource属性时,无法修改项目集合 - Items collection cannot be modified when the DataSource property is set 错误:其他信息:设置DataSource属性时,不能修改项目集合 - ERROR: Additional information: Items collection cannot be modified when the DataSource property is set System.ArgumentException:设置DataSource属性时,不能修改Items集合 - System.ArgumentException: Items collection cannot be modified when the DataSource property is set 设置DataSource属性后,将无法修改项目集合。 C# - Items collection cannot be modified when the DataSource property is set. c# System.ArgumentException:“设置 DataSource 属性时无法修改项目集合。” C# Windows Forms - System.ArgumentException: 'Items collection cannot be modified when the DataSource property is set.' C# Windows Forms
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM