3

我有Winform Listbox已经绑定到data source.

var custList=Cusomer.CustomerList();
lstbox.DataSource=custList;
`enter code here`
lstbox.DisplayMember="CustName";
lstbox.ValueMemebr="CustId";

现在我想添加一个名为“All”的文本,list box以便它应该显示为第一个listitem。此外,通过添加的列表项binding也应该存在于那里。我的想法是当用户选择“全部”选项时,所有列表项都必须自动选择。

知道如何添加新的文本值吗?

谢谢。

4

2 回答 2

2

使用ListBox.Items.Insert并指定0为索引。

ListBox1.Items.Insert(0, "All");
于 2013-06-20T11:43:37.887 回答
0

希望这会帮助你。

    void InitLstBox()
    {
        //Use a generic list instead of "var"
        List<Customer> custList = new List<Customer>(Cusomer.CustomerList());
        lstbox.DisplayMember = "CustName";
        lstbox.ValueMember = "CustId";
        //Create manually a new customer
        Customer customer= new Customer();
        customer.CustId= -1;
        customer.CustName= "ALL";
        //Insert the customer into the list
        custList.Insert(0, contact);

        //Bound the listbox to the list
        lstbox.DataSource = custList;

        //Change the listbox's SelectionMode to allow multi-selection
        lstbox.SelectionMode = SelectionMode.MultiExtended;
        //Initially, clear slection
        lstbox.ClearSelected();
    }

如果您想在用户选择 ALL 时选择所有客户,请添加此方法:

    private void lstbox_SelectedIndexChanged(object sender, EventArgs e)
    {
        //If ALL is selected then select all other items
        if (lstbox.SelectedIndices.Contains(0))
        {
            lstbox.ClearSelected();
            for (int i = lstbox.Items.Count-1 ; i > 0 ; i--)
                lstbox.SetSelected(i,true);
        }
    }

当然,不要忘记设置事件处理程序:)

 this.lstbox.SelectedIndexChanged += new System.EventHandler(this.lstbox_SelectedIndexChanged);
于 2013-06-20T13:07:05.750 回答