列表框错误:设置了DataSource属性时,无法修改项目集合 [英] listbox error: Items collection cannot be modified when the DataSource property is set

查看:287
本文介绍了列表框错误:设置了DataSource属性时,无法修改项目集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个窗口形式的列表框,一个在左侧,一个在右侧.这 第一个列表框有一些项目,而第二个列表框为空.也有 是2个列表框之间的2个按钮,用于将项目移入/移出 第一个和第二个列表框

I have 2 listboxes in a window form, one on left and one on right. 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

我的问题是,将数据绑定到第一个列表框后(从 数据库,使用DisplayMember和ValueMember),我尝试移动1 从第一个列表框到第二个列表框的项目,我想要 选定的项目也可以通过以下方式从第一个列表框中删除:

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:

    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.

它显示错误消息无法修改项目集合 设置DataSource属性时."

it displays error message "Items collection cannot be modified when the DataSource property is set."

任何人都可以给我解决我的问题的方法.

can any one give me the solution to my problem.

推荐答案

向您的DataTable对象添加一个布尔列,例如IsSelected.

Add a boolean column to your DataTable object, something like IsSelected.

然后将列表框1直接绑定到表,而不是直接将其绑定到表.使用设计器将2个绑定源添加到您的表单.并将此代码放在文件后面的代码中.

Then instead of binding your listbox1 directly to the table, bind it to a BindingSource. Add 2 bindingsources to your form using the designer. 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;
        }
    }    

现在,您的列表框都连接到相同的数据表,并基于IsSelected属性/列进行过滤.只需将此列设置为true或false,它就会在框与框之间翻转.您的按钮事件处理程序可能如下所示:

Now your listboxes are both connected to the same datatable and filtered based on the IsSelected property / column. Just set this column to true or false and it will flip from box to box. 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;
     }
}

这行得通!

如果使用类型化的数据集,事情将变得简单多了.然后,大多数绑定都可以在设计器中完成,您后面的代码将缩小为20行代码....

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....

这篇关于列表框错误:设置了DataSource属性时,无法修改项目集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆