Add Items to the ComboBox - c#

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.

Related

add "please select" row in combobox [duplicate]

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.

Change Textboxcell to a Comboboxcell at run time

I'm using MySQL .net connector to fill a Datagridview using Mysqladapter and Datagridview.Bindingsource. That works good, but I want to change one thing:
In the table which is filled to the DataGridview, there is a column with a text type. The cells in this columns are displayed as a Datagridviewtextboxcell in the datagridview, but I want to change it to DataGridviewComboboxCell (the users should select between ~10 items).
I already tried a lot but nothing worked as it should. The Columns in the DataGridview are readonly, I cannot change DefaultCellTemplate to a DataGridviewComboboxCell, cause it doesn't inherit DataGridviewTextboxcell.
I also tried this: Gridview - convert textboxcell to comboboxcell and back and I think my problem could be solved over this way, but with this solution I have also 1 problem: It doesnt show a DropDown Button.
Any help will be greatly appreciated.
To do this you need to add a new DataGridViewComboBoxColumn to the grid and then hide the text box column.
I show this using code below but you can do the same using the designer (just set the properties I set in code using the designer).
The key things to note are:
DataPropertyName refers to a property of the grid's data source - likely your text box source
You need to provide the column with its own data source
DisplayMember and ValueMember refer to the data source of the column
Here is the code to add the column:
// Here I do this in the form constructor - there are other places you can do it
public Form1()
{
InitializeComponent();
DataGridViewComboBoxColumn col = new DataGridViewComboBoxColumn();
// You need to set some properties on the column to make it work
// Datasource is the source (usually a list) of objects to show in the combobox
col.DataSource = dataSource;
col.DataPropertyName = "ColumnInGridDataSource";
col.DisplayMember = "DisplayProperty";
col.ValueMember = "ValueProperty";
dataGridView1.Columns.Add(col);
// This hides the textboxcolumn
dataGridView1.Columns["YourTextBoxColumnName"].Visible = false;
}
In the answer you linked, before the line:
dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex] = cb;
Try adding:
cb.DisplayStyle = DataGridViewComboBoxDisplayStyle.CHOOSE_ONE;
cb.FlatStyle = FlatStyle.CHOOSE_ONE;
I am not sure how exactly you want to style your comboboxes, so instead of "CHOOSE_ONE", try out the styles and pick the style you want.
Edit: Seems like you're not changing it to a combobox at all. Try this:
var values = new List<string> { "a", "b", "c" };
var cell = new DataGridViewComboBoxCell();
cell.DataSource = values;
dataGridView1[col, row] = cell;

How to get value of ValueMember of datagridviewcomboboxcolumn

Friends, I'm using datagridviewcomboboxcolumn as column index 1 in my datagridview. I've fetched data from access database table and populated the datagridviewcomboboxcolumn by following manner:
for (int i = 0; reader.Read(); i++)
{
cmbBusCode.Items.Add(reader["BUSINESS_CODE"] + "-" + reader["BUSINESS_DESCRIPTION"]);
cmbBusCode.ValueMember = "BUSINESS_CODE";
}
Then I'm writing this:
cmbBusCode.DisplayIndex = 1;
cmbBusCode.Width = 200;
cmbBusCode.Name = "Code";
cmbBusCode.HeaderText = "Code";
And adding this column as
dgView.Columns.Add(cmbBusCode);
Combobox is being populated and I can select any one from the list. Now when I'm saving data I want to get the ValueMember of the selected item. To get this value I'm using following code but It's giving the string representation of the field "BUSINESS_CODE" not the value..Please help me so that get ValueMemeber of the selected item..
foreach (DataGridViewRow row in dgView.Rows)
{
string cd = row.Cells["Code"].Value.ToString();
}
The "item" you are adding to the column doesn't have a "BUSINESS_CODE" column (essentially, the item as you add it is simply a string), so that doesn't work.
What you need to do is assign items that contain multiple columns. One must be the BUSINESS_CODE column (as it is this column you want to be the value for the underlying field in the DataGridView), the other should be a display column that contains the concatenated value you're adding at the moment (DisplayMember and ValueMember).
Easiest would be to create a typed data set, add a table that contains the two columns I described and fill the table with the data from the data reader.
Then, add the table as the data source for the column.
You can try adding a DataGridViewComboBoxCell instead of a string to the cmbBusCode.Items collection. You can then specify Value in the cell. I'm not sure if this will work, but it's worth a try.

c# datagridview having different datasources for different columns

I have a datagridview which has multiple text columns and a single comboboxcolumn. I need to specify a datasource for the iems of the comboboxcolumn and another datasource for the other text columns. I have tried the following sample code but it does not work.
dgv1.DataSource = DataSet1.Tables[0];
string[] managerList = Array.ConvertAll(DataSet2.Select(), row => (string)row[0]);
comboboxcolumn1.DataSource = managerList;
The managerList array has the entries that are to be populated into the combobox but they never show up.
Is that so that I can not have a separate datasource for a comboboxcolumn and its parent datagridview?
Thanks in advance.
I have checked with the following code and it works fine
string[] arr = "This Should Get Displayed".Split(); //managerList in your case
dataGridView1.DataSource = MyData(false);
(dataGridView1.Columns["Column1"] as DataGridViewComboBoxColumn).DataSource = new BindingSource(arr, null); // Bind to the column of grid
Can you try assigning it as referencing it as a column of your datagridview.
This displays the text split on space in my combobox.
When you are using string array no need to specify Display and Value member for the column
EDIT
If you have a DataTable you can also do it in this fashion
(dataGridView1.Columns["Column1"] as DataGridViewComboBoxColumn).DataSource= datatable;
(dataGridView1.Columns["Column1"] as DataGridViewComboBoxColumn).DisplayMember="columnname";
(dataGridView1.Columns["Column1"] as DataGridViewComboBoxColumn).ValueMember="columnname";

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