add "please select" row in combobox [duplicate] - c#

I have a combobox which is binded to a list. I've been trying to work out how to have the first item in the combobox when it's loaded a "--Please Select--" before the data from the list is loaded.
I have tried this,
cbUpdate.DataSource = _names;
cbUpdate.Items.Insert(0, "-Select-");
cbUpdate.SelectedIndex = 0;
cbUpdate.DisplayMember = "Name";
But this gives the errro,
Items collection cannot be modified when the DataSource property is
set.
I understand the error, but I am unsure of how to solve it. I've trying to set the Text of the combobox to "Please Select" but that doesn't work.
var names = new BindingList<Names>();

You are setting the DataSource and Adding an Item After which will eventually throw an error. A better approach would be to add the item "-Select-" first to the combobox then try to add next the items in the list using a foreach statement instead of binding the list to the combobox.
cbUpdate.Items.Clear();
cbUpdate.Items.Add("-Select-");
foreach (string item in thelsit)
{
cbUpdate.Items.Add(item.ToString());
}
cbUpdate.SelectedIndex = 0;

You have to decide, either use the Items property, and fill in all your options. Or use a DataSource with all the options.
In any case, for the "--Please Select--" entry, you either need to have it as one of the options inside the Items, or DataSource. Or you could just set the SelectedText property.

Try inserting the '--Select--' text in the names list before setting it to the datasource.
Example:
List<Person> list = new List<Person>() {
new Person("Jon"),
new Person("Ram"),
new Person("Rin")
};
list.Insert(0, new Person("--Select"));
comboBox1.DataSource = list;
comboBox1.DisplayMember = "Name";
comboBox1.Items.Clear();

There are other ways to achieve this. It depends on how you are retrieving the values from your database.
If you are using a select statement, you can do a union like
// Oracle
SELECT 0, "---- Please Select ----" from dual
UNION
SELECT [value], [name] from [table]
The result of which you can assign as the data source.
Another option is to remove the DataSource property and once you have the data in hand, iterate through the record set and add items one by one, with 0 and "---- Please Select ----" as the ValueMember and DisplayMember for the first item.

Related

C# Windows Forms ComboBox How to Set default value to "Select " initially loads data from datatable

I searched the site found several references to what I am looking to do. None worked in my case.
This seems like a simple problem. I am simply trying to set the default value to "--Select--".
I am filling the comboBox from a datatable from a database
Admin_BL admBL = new Admin_BL();
//populates datatable from database
dtBlds = admBL.GetActiveBuildings();
cmbBuilding.DataSource = dtBlds;
cmbBuilding.Text = "--Select--";
cmbBuilding.DisplayMember = "Building";
cmbBuilding.ValueMember = "Building";
I have used this also:
cmbBuilding.Items.Insert(0, "Select Bld");
This seems like a simple task I am not sure why this is not working in windows forms
I would appreciate the help Thank You!
The issue here is that you're binding to an object and that object does not contain an entry for "-- Select --". Either you need to add this entry during the query:
SELECT 0 AS ID, '-- Select --' AS Building
UNION ALL
SELECT ID, BUILDING FROM <TABLE>
Then when you bind you'll find "-- Select --" is the first item.
If you don't want to change your query you can just insert a new row into the datatable once you've retrieved the data.
Assuming you've only got 2 columns in your datatable (ID and Building):
DataRow row = dtBlds.NewRow();
row[0] = 0;
row[1] = "-- Select --";
dtBlds.Rows.InsertAt(row, 0);
Once you've done this you can do the binding:
cmbBuilding.DataSource = dtBlds;
cmbBuilding.DisplayMember = "Building";
cmbBuilding.ValueMember = "Building";
considering "--Select--" is first item in your combobox, in runtime you select the first item by its index (of course it can be set in any other index like third item then index would be 2):
cmbBuilding.SelectedIndex = 0;
To add "--Select--" in function that populates the combobox items, before anything add "--Select--" to its items and then the items from database:
cmbBuilding.Items.Add("--Select--");
//add other items from db.

Combo box with default value like --Select Gender --

I have a combo box which I want the default value to be -- Select Gender --
I have tried the following coding, and I got this error
Items collection must be empty before using ItemsSource.
Please help
cboGender.ItemsSource = null;
cboGender.DisplayMemberPath = "Display";
cboGender.SelectedValuePath = "Value";
cboGender.SetBinding(ComboBox.ItemsSourceProperty, oBinding);
cboGender.Items.Insert(0, "--Select Gender--");
cboGender.SelectedIndex = 0;
Add "--Select Gender--" to your Collection before binding it to the ItemsSource (if you want it as first, remember to use Insert(0, ) and then after binding it, set the SelectedIndex to it.
May be you should try to call
cboGender.Items.Clear();
before the insertion of the default item.
OR
Just create your data source with the default value item before inserting any value in the combo box and write something like this:
cboGender.Items.Clear();
cboGender.ItemsSource = dataSource;
where dataSource would be the list with the all items.
You can use
<ComboBox x:Name="cboGender"
Text="--Select Gender--" />
if you don't need to choose this default value again after first selection

DataSource, bind more then 1 value

I want to bind more then 1 columns to drop down list, so that I can get the column values when user clicks a button,
ddlListMine.DataSource = GetSomeChickens();
ddListMine.DataTextField = "ChickenName";
ddListMine.DataValueField= "NumberOfEggsChickenLay";
ddListMine.Items.Insert(0, new ListItem("Please Please Please Select....", "0"));
ddListMine.DataBind();
I have another column "ChickenType", which I want to access in Selected Index change column.
GetSomeChickens(); returns 6 columns, including ChickenName, NumberOfEggsChickenLay, ChickenType and so on...
Edit
Off course, I can call database again in selected index change method, but there must be a way around i think
The DropDownList doesn't hold the entire object during the binding, only the Text and Value as defined by DataTextField and DataValueField.
In order to get a selected object back, you can have a method to get the ChickenType by passing the ChickenName using Linq like this.
List<Chicken> Chickens = GetSomeChickens();
Var Chicken= Chickens.FirstOrDefault(c => c.ChickenName== ddlListMine.SelectedItem.Text);
if(Chicken!= null)
{
string ChickenType = Chicken.ChickenType ;
}

Add Items to the ComboBox

I have a ComboBox control.
I bind to this control to the DataSet table.
Here is the code:
comboBox.Items.Add(("Select"));
comboBox.DataSource = DataSet.ColorTable;
comboBox.DisplayMember = DataSet.ColorTable.ColorNameColumn.ColumnName;
comboBox.ValueMember = DataSet.ColorTable.ColorIDColumn.ColumnName;
This result I get:
I want to display on the top of the list SELECT: word. So I need to add addition Item to the comboBox control.
Here how I implement it:
cmbCategory.Items.Add(("Select"));
But the result is still the same as above. I get only colors without SELECT: word on the top of the list.
Any idea how I can add this string-SELECT: to the ComboBox control and set to this string ValueMember?
Use Insert method instead.
cmbCategory.Items.Insert(0, "Select");
Note : Put this code after the databind.
You can add the collections of color to an array or a dataset (if you are getting them from database) first and then add items "select", then add each elements of the array or a column of the dataset.
Do this in Form_Load function and wherever there are changes made in color collections array or database.
//This will set Display member and value member
comboBox.DisplayMember = "ColorName";
comboBox.ValueMember = "ColorCode";
//This will add a new row to table in binded dataset
DataRow dr = dal.MyProperty_dsColors.Tables["ColorInfo"].NewRow();
dr["ColorName"] = "Select Color"; //SomeName
dr["ColorCode"] = 001; //Some ID
dal.MyProperty_dsColors.Tables["ColorInfo].Rows.Add(dr);
//binding dataSource
comboBox.DataSource = dal.MyProperty_dsColors.Tables["ColorInfo"];
What would also help you is that you set the ComboBox without having to 'Select' it when the popup arrives...
Select your ComboBox, under the properties tab, select Appearance->Drop Down Style and select DropDownList.
If we want to add manually values in a combobox (for example integers) this can be done using a for loop:
// sample code
int lower=1;
int higher=500;
for (int i=lower; i<=higher; i++)
combo_values.Items.Add(i.ToString());
Note that you have to use the int.Parse(combo_values.Text) command to read a value.

Insert a default row into a combobox that is bound to a datatable?

On a winform there is a combobox that derives its information from a datatable. The datatable draws from a database list.
this.cboList.DataSource = pullData();
this.cboList.DisplayMember = "fieldA";
Once the DataSource is set I am not able to insert a default row (ie *) as the first item in the combobox.
I tried this:
this.cboList.Items.Insert(0,"*");
Is there a way to insert in the combobox after the datasource is set or should this be done in the datatable?
UPDATE1:
The solution looks something like this:
var list = mydt.AsEnumerable().Select(row => row.Field<string>(fieldName)).ToList();
list.Insert(0, "*");
Where mydt is a populated datatable and fieldName is a variable holding the database field name.
Don't modify your data at the source just to make your UI work. Instead, perhaps extract your column into a list that you can modify before attaching it to the combo box.
var list = table.AsEnumerable().Select(row => row.Field<string>("fieldA")).ToList();
list.Insert(0, "*");
this.cboList.DataSource = list;
If a "Select None", or "*" is a valid select option it needs to come from the binding source object. I have done this in the past by adding a default record to a collection before binding it to a combo box.

Categories