简体   繁体   中英

Combo box custom items and data bound items

I've made combo box and added item and loaded data from datasource function getBS() returns bindingsource.

comboBox1.Items.Insert(0, "ALL");
comboBox1.DataSource = getBS();

when I comment datasource it shows only item "all", but when the code is like this it shows only data but it doesn't show attribute "all". is there a way to make it all together? To show attribute "all" and rest of data?

comboBox1.DataSource = getBS();
comboBox1.Items.Insert(0, "ALL");

You need to populate the datasource, then add too it. The point of inserting the item at index 0, is so that you can add it to the existing set of ListItems.

If you add your Item, then set the datasource, your clearing datasource and resetting it.

MSDN says

A data source can be a database, a Web service, or an object that can later be used to generate data-bound controls. When the DataSource property is set, the items collection cannot be modified .

So what are your options now?

BindingSource GetBS(bool addAll = false)
{
    ......
    con.Open(); 
    cmd = new SqlCommand("uspPodruznicaSelect", con); 
    da.SelectCommand = cmd; 
    da.SelectCommand.CommandType = CommandType.StoredProcedure; 
    da.Fill(dbtable); 

    if(addAll)
    {
        DataRow dr = dbTable.NewRow();
        dr["ItemID"] = 0;
        dr["ItemData"] = "ALL";
        dbTable.Rows.InsertAt(dr, 0);
    }

    bsource.DataSource = dbtable; 
    con.Close(); 
    return bsource;
}

Adding the ALL directly to the DataTable returned by your sp. Of course I don't know the exact names of the fields that are involved in this table, but this is just to give you the idea. Possibly you could have other problems if the sp returns a table with more fields and these fields are NOT NULLABLE. In this case you need to add a dummy value also for these field in the new row.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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