How to get value from combobox in c#? - c#

I can't get value from ComboBox in WinForms using C#.
I have a ComboBox populated with a list of values and I have set ValueMember and DisplayMember.
Now, I have to find the value of the selected ComboBox item and select the matched item in UI.
Here is what I mean:-
I loaded the ComboBox like this :-
var list = (from l in db.Loc
orderby l.LName ascending
select l).ToList();
list.Insert(0, new Loc { ID = "-1", Name = "--Select--" });
cmb1.BindingContext = new BindingContext();
cmb1.DataSource = list;
cmb1.DisplayMember = "Name";
cmb1.ValueMember = "ID";
Now on an event, I am trying to match value (ID) and select the item. It's easy if I match Text property:
cmb1.Text = data.Name;
But How to match the value?
Something like this:-
cmb1.Value = data.ID;

If you only know the ID of the item you can also use:
cmb1.SelectedValue = data.ID;

This should work:
cmb1.SelectedValue = data.ID;

Why would you like to assign you "matched" value to the ComboBox Value property?
As soon as you have correctly set DisplayMember and ValueMember and you DataSource implements both as properties the values will be autoamatically "matched", e.g. you can read the Value property in you event handler to get this "matched" value.

data must be in the list binded to the combobox, then:
cmb1.SelectedItem = data
or, if it's not (you retrieved another instance from somewhere):
cmb1.SelectedValue = data.ID

First of all: cmb1.Text = text; changes the text of the ComboBox to the specified value. It doesn't select the item with the text that matchs the specified value.
Use cmb1.SelectedValue = value; to select the item with the speciefied value.

You can get the index using Combo1.SelectedIndex property. You can get the item using either Combo1.SelectedItem or Combo1.Items[Combo1.SelectedIndex]

Related

How to insert first item in combo box with text "SELECT" with default value 0 in C# windows application

I am using C# windows application. My code is as below
var categoryList = _objCategoryManager.GetAll();
cmbCategory.DisplayMember = "Name";
cmbCategory.ValueMember = "Id";
cmbCategory.DataSource = categoryList;
Here categoryList is of type IEnumerable. I want to insert item in ComboBox at 0 index i.e."--SELECT--"
You cannot insert item to your ComboBox after data binding. Instead insert the item in a copy of your data source before, then do the binding.
If categoryList is IEnumerable<T> and not a List<T> then you should copy it to a List<T> so that you can add your default value at the first index:
var categoryList = _objCategoryManager.GetAll().ToList();
categoryList.Insert(0, new Category {Id = -1, Name = "--SELECT--"});
Simply insert it into your list, so something like
var categoryList = _objCategoryManager.GetAll().ToList();
cmbCategory.DisplayMember = "Name";
cmbCategory.ValueMember = "Id";
categoryList.Insert(0, new Category() { Name = "--SELECT--"} );
cmbCategory.DataSource = categoryList;
categoryList.ToList().Find(o => o.ID == Convert.ToInt32(0)).Name = "--SELECT--";
Using LINQ, you can find the object you want to change (after binding) and modify that item.
Otherwise if you are adding an object into the list:
categoryList.ToList().Add(obj); // This should show the new item in the combo box
Ultimately your .GetAll() method should have returned the first one to be "--SELECT--" instead of trying to modify it afterwards.

combobox item selected To be fixed

I had a databound combobox in my windows form I populate it by a function deptload() IN FORM LOAD
public void DeptcomboLoad()
{
DataTable dt = depttrans.getDeptName();
Cmb_Department.DataSource = dt;
Cmb_Department.DisplayMember = "DepartmentName"; //CHAR
Cmb_Department.ValueMember = "DepartmentPK"; //INT
}
Now when an employee of a department (say accounts DepartmentName="Accounts " , DepartmentPK=23 ) login I want the ComboBox text to be selected as "acounts "
and when I go to get the selected value of the ComboBox I should get 23
I tried
Cmb_Department.selectedtext="Accounts"
Cmb_Department.Text="Accounts"
but its not giving the selected value
Can anyone give a suggestion
Instead of trying to put a value INTO the combobox, try to GET the SelectedItem like this:
string txt= Cmb_Department.SelectedItem.Text
or just:
string txt= Cmb_Department.SelectedText
To change selected value of the combobox you can use
SelectedItem property or SelectedIndex.
Index must be exact number in your data sourse, and Item must be exact object from datasource
You can get it to select the right item by issuing something like this:
Cmb_Department.SelectedValue = 23;
Where 23 comes from some other variable, maybe on another object, maybe from a local variable, whatever works in your case.
Now, to get the selected value you can use this statement:
var val = Cmb_Department.SelectedValue;
To get the selected text (which would be the text associated with the value):
var text = ((DataRow)Cmb_Department.SelectedItem)["DepartmentName"];
The reason I'm prescribing the aforementioned is because the SelectedText property is volatile, and the Text property doesn't always work based on how the DropDownStyle is set.
However, some would probably argue to get the same as the aforementioned you could issue this statement:
var text = Cmb_Department.Text;

change selecteditem of dropdownlist after binding

i have a droplist in page that i bind this with code
Category catObj = new Category();
dropCat.DataSource = catObj.GetAllCategory();
dropCat.DataTextField = "Title";
dropCat.DataValueField = "CategoryID";
dropCat.DataBind();
i want change selected item of droplist with ths code
dropCat.SelectedIndex = Convert.ToInt32(catObj.ParentId);
but this code cant change the selected item
please help me
thank you all
I'll assume that you're trying to select by value and not by index since catObj.ParentId is likely to contain a CategoryId. In case my assuption is correct, you'll need to do this
dropCat.SelectedValue = catObj.ParentId.ToString();
DropDownList.SelectedIndex property refers to a position inside Items collection and not about the value of the item.

replace true/false in datagridview columns

I have a datagridview which I fill it as below :
var q= repository.GetStudents();//
dataGridView1.DataSource = null;
dataGridView1.Columns.Clear();
dataGridView1.DataSource = q;
dataGridView1.Columns.RemoveAt(1);
//Remove IsActive
//Cause I want to have my own implementation
dataGridView1.Columns[0].DataPropertyName = "StudentID";
dataGridView1.Columns[0].HeaderText = "Studunet ID";
dataGridView1.Columns[1].DataPropertyName = "IsActive";
dataGridView1.Columns[1].HeaderText = "Status";
The "IsActive" property is of boolean Type. When the "IsActive" cell is being displayed, it show true/false. I want to replace it with my own custom value.
I read this and this posts but I could not resolve my problem.
You can use the CellFormatting event of the DataGridView, e.g.:
void dataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
var grid = (DataGridView)sender;
if (grid.Columns[e.ColumnIndex].Name == "IsActive")
{
e.Value = (bool)e.Value ? "MY_TEXT_FOR_TRUE" : "MY_TEXT_FOR_FALSE";
e.FormattingApplied = true;
}
}
EDIT (as per comment):
It's very similar to what you're doing now, just remove the bound column and add a new column of the desired type and set the DataPropertyName properly e.g. :
this.dataGridView1.Columns.Remove("COL_TO_CUSTOMIZE");
var btnCol = new DataGridViewDisableButtonColumn();
btnCol.Name = "COL_TO_CUSTOMIZE";
btnCol.DataPropertyName = "COL_TO_CUSTOMIZE";
var col = this.dataGridView1.Columns.Add(btnCol);
Note that this append the column at the end, but you can decide the position of the column by using dataGridView.Columns.Insert method instead of Add.
One of the funky things about a DataGridViewComboBoxColumn is that you can give it one data source that has a column of values to lookup and a column of values to show, and you can bind it to another column of values and then it will perform the lookup for you
So, suppose your collection q of Students (or whatever they are) has an IsActive true/false and you want this to show as "All the time", or "Not a chance".. Let's hash together a combobox that does this:
var cb = new DataGridViewComboBoxColumn();
cb.DisplayMember = "DisplayMe"; //the related text to show in the combo
cb.ValueMember = "ValueToLookup"; //the name in the combo's lookup list
cb.DataPropertyName = "IsActive"; //the name of your property on Student, to look up
cb.DataSource = "All the time,Not a Chance"
.Split(',')
.Select(s => new { DisplayMe = s, ValueToLookup = (s[0] == 'A') } )
.ToList();
It doesn't really matter how we generat the combo's datasource; here I've made a string into a List<anonymous_string+bool> by splitting, then selecting a new anonymous type with the two property names I need; you can use anything that has some named properties - a List of KeyValuePair, Tuple, whatever..
The critical thing is that the combo can read the q.IsActive bool you cited in DataPropertyName, look that bool up in its list in the property named in the ValueMember, then display the property named in the DisplayMember. It works for editing too, so the user can choose a new item from the combo and the translation works back the other way - "what does the user choose? what is the value of its property named in ValueMember, put that value into the student IsActive property named in DataPropertyName".. And it doesnt stop at bools either; the value member can be anything - an int, date etc

Setting dropdownlist selecteditem programmatically

I want to set the selecteditem attribute for an ASP.Net dropdownlist control programmatically.
So I want to pass a value to the dropdownlist control to set the selected item where the item is equal to the passed value.
Assuming the list is already data bound you can simply set the SelectedValue property on your dropdown list.
list.DataSource = GetListItems(); // <-- Get your data from somewhere.
list.DataValueField = "ValueProperty";
list.DataTextField = "TextProperty";
list.DataBind();
list.SelectedValue = myValue.ToString();
The value of the myValue variable would need to exist in the property specified within the DataValueField in your controls databinding.
UPDATE:
If the value of myValue doesn't exist as a value with the dropdown list options it will default to select the first option in the dropdown list.
ddlData.SelectedIndex will contain the int value To select the specific value into DropDown :
ddlData.SelectedIndex=ddlData.Items.IndexOf(ddlData.Items.FindByText("value"));
return type of ddlData.Items.IndexOf(ddlData.Items.FindByText("value")); is int.
Here is the code I was looking for :
DDL.SelectedIndex = DDL.Items.IndexOf(DDL.Items.FindByText("PassedValue"));
Or
DDL.SelectedIndex = DDL.Items.IndexOf(DDL.Items.FindByValue("PassedValue"));
Well if I understood correctly your question. The Solution for setting the value for a given dropdownlist will be:
dropdownlist1.Text="Your Value";
This will work only if the value is existing in the data-source of the dropdownlist.
If you need to select your list item based on an expression:
foreach (ListItem listItem in list.Items)
{
listItem.Selected = listItem.Value.Contains("some value");
}
Just Use this oneliner:
divisions.Items.FindByText("Some Text").Selected = true;
divisions.Items.FindByValue("some value").Selected = true;
where divisions is a dropdownlist control.
Hope it helps someone.
var index = ctx.Items.FirstOrDefault(item => Equals(item.Value, Settings.Default.Format_Encoding));
ctx.SelectedIndex = ctx.Items.IndexOf(index);
OR
foreach (var listItem in ctx.Items)
listItem.Selected = Equals(listItem.Value as Encoding, Settings.Default.Format_Encoding);
Should work.. especially when using extended RAD controls in which FindByText/Value doesn't even exist!
ddList.Items.FindByText("oldValue").Selected = false;
ddList.Items.FindByText("newValue").Selected = true;
On load of My Windows Form the comboBox will display the ClassName column of my DataTable as it's the DisplayMember also has its ValueMember (not visible to user) with it.
private void Form1_Load(object sender, EventArgs e)
{
this.comboBoxSubjectCName.DataSource = this.Student.TableClass;
this.comboBoxSubjectCName.DisplayMember = TableColumn.ClassName;//Column name that will be the DisplayMember
this.comboBoxSubjectCName.ValueMember = TableColumn.ClassID;//Column name that will be the ValueMember
}
Safety check to only select if an item is matched.
//try to find item in list.
ListItem oItem = DDL.Items.FindByValue("PassedValue"));
//if exists, select it.
if (oItem != null) oItem.Selected = true;
ddlemployee.DataSource = ds.Tables[0];
ddlemployee.DataTextField = "Employee Name";
ddlemployee.DataValueField = "RecId";
ddlemployee.DataBind();
ddlemployee.Items.Insert(0, "All");

Categories

Resources