Combobox's elements filtering - c#

I have combobox1 and comboox2 and in combobox1 my elements are A,B,C and combobox2 1,2,3,4,5,6...
A related 1,2,3 and B related 3,4 and C related 5,6.
When I choose "A" I want to see just 1,2,3 ; when select "B" just 3,4 etc.
How can I imagine it ?
I tried to do in selected index changed but I didn't

Try this , make a class like this:
public class Data
{
public string Name { get; set; }
public List<int> Values { get; set; }
}
then in your form have a variable like this:
private List<Data> data = new List<Data>
{
new Data{Name="A",Values=new List<int>{1,2,3}},
new Data{Name="B",Values=new List<int>{4,5}},
new Data{Name="C",Values=new List<int>{6,7}},
};
then in the form's constructor :
comboBox1.DisplayMember = "Name";
comboBox1.DataSource = data;
comboBox1.SelectedIndex = 0;
then on the combobox1's selectedindex changed event do like this:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
int index = comboBox1.SelectedIndex;
comboBox2.DataSource = data[index].Values;
}
It should work.

Related

ComboBox items not updating when underlying ObservableCollection changes

I have a ComboBox and an ObservableCollection set as DataSource for that ComboBox.
When I programmatically add/remove items from the observable collection, nothing changes in the ComboBox.
What am I doing wrong?
Part 2: tried to put a BindingSource as a proxy for ObservableCollection. When programmatically added/removed items from ObservableCollection, no event like ListChanged or similar fired.
How can I make a ComboBox automatically update its list when underlying collection changes?
public Form1()
{
InitializeComponent();
comboBox1.DataSource = new ObservableCollection<MyItem>(
new []
{
new MyItem() { Name = "AAA"},
new MyItem() { Name = "BBB"},
});
}
private void Button3_Click(object sender, EventArgs e)
{
// Nothing changes in the ComboBox when I add a new item to ObservableCollection
((ObservableCollection<MyItem>)(comboBox1.DataSource))
.Add(new MyItem() { Name = Guid.NewGuid().ToString()});
}
}
public class MyItem
{
public string Name { get; set; }
}
It helps to wrap a list in a BindingList<T>. Here a little test code:
public partial class Form1 : Form
{
private readonly List<string> _coll = new List<string> { "aaaaa", "bbbbb", "ccccc" };
private readonly BindingList<string> _blist;
private readonly Random _rand = new Random();
private const string Templ = "mcvnoqei4yutladfffvtymoiaro875b247ytmlarkfhsdmptiuo58y1toye";
public Form1()
{
InitializeComponent();
_blist = new BindingList<string>(_coll);
comboBox1.DataSource = _blist;
}
private void AddButton_Click(object sender, EventArgs e)
{
int i = _rand.Next(Templ.Length - 5);
string s = Templ.Substring(i, 5);
_blist.Add(s);
}
}
Note that you have to make the changes (Add, Remove etc.) to the BindingList. The BindingSource works the same way.

binding to a combobox getting different results when using using SelectedValue

I have bound to my combobox this simple class:
public class Company
{
public Guid CorporationId { set; get; }
public Guid TokenId { set; get; }
public string Name { set; get; }
}
And this is my binding:
private void FillCompaniesComboBox()
{
_doneLoadingComboBox = false;
comboBox_Companies.Items.Clear();
if (CurrentSettings.AllCompanies.Count == 0)
{
return;
}
bindingSource1.DataSource = CurrentSettings.AllCompanies;
comboBox_Companies.DataSource = bindingSource1.DataSource;
comboBox_Companies.DisplayMember = "Name";
comboBox_Companies.ValueMember = "CorporationId";
comboBox_Companies.SelectedIndex = 1;
_doneLoadingComboBox = true;
}
When I attempt to get the value of the selected item, I'm getting different results. Here is the code I am using to get my value:
private void comboBox_Companies_SelectedIndexChanged(object sender, EventArgs e)
{
if (!_doneLoadingComboBox && comboBox_Companies.SelectedIndex == -1)
{
return;
}
var value = (Company)comboBox_Companies.SelectedValue;
Console.WriteLine("Value: " + value.CorporationId);
}
Here is what is happening:
This one works at intended:
And this is were it is causing an issue:
Am I not retrieving the data correctly? I need the Company information that it is bound to.
Okay so here's what you need to do...
Assuming that your CurrentSettings.AllCompanies is an IList<Company> that you've already populated with data, here's what your code should look like:
public class ComboBoxItem {
// your class
private Company Comp;
}
private readonly BindingSource _bsSelectedCompany = new BindingSource();
private readonly ComboBoxItem _comboBoxItem = new ComboBoxItem();
// your main form method
public MainForm() {
// initialization code...
InitializeComponent();
// prevents errors in case your data binding objects are empty
ResetComboBox(comboBox1);
comboBox1.DataBindings.Add(new Binding(
"SelectedItem",
_bsSelectedCompany,
"Comp",
false,
DataSourceUpdateMode.OnPropertyChanged
));
comboBox1.DataSource = CurrentSettings.AllCompanies;
comboBox1.DisplayMember = "Name";
}
// simple method for resetting a given combo box to a default state
private static void ResetComboBox(ComboBox comboBox) {
comboBox.Items.Clear();
comboBox.Items.Add("Select a method...");
comboBox.SelectedItem = comboBox.Items[0];
}
By doing this, you're able to just use _comboBoxItem to safely get the information about your selected item without having to potentially Invoke it (in the case of accessing it on a separate thread).

c# ComboBox, save item with value and text

I am trying to add an object ITEM with TEXT and VALUE to a ComboBox so I can read it later
public partial class Form1 : Form
{
ComboboxItem item;
public Form1()
{
InitializeComponent();
comboBox1.Items.Add(new ComboboxItem("Dormir", 12).Text);
}
private void button1_Click(object sender, EventArgs e)
{
ComboboxItem c = (ComboboxItem)comboBox1.SelectedItem;
label1.Text = c.Text;
label2.Text = c.Value.ToString();
}
}
The problem is, I cant add the full Item because isn't a string...and give an exception at beginning of click event
Extra information:
This ComboboxItem, its a class that I created with 2 parameters, string, and int
public class ComboboxItem
{
public string Text { get; set; }
public object Value { get; set; }
public ComboboxItem(string texto, double valor)
{
this.Text = texto;
this.Value = valor;
}
}
You could (should) set the displaymember and valuemember in another place, but...
public Form1()
{
InitializeComponent();
comboBox1.DisplayMember="Text";
comboBox1.ValueMember ="Value";
comboBox1.Items.Add(new ComboboxItem("Dormir", 12));
}
Create the ComboboxItem class and override the ToString method.
The ToString method will be called to visualize the item. By default, ToString() returns the typename.
public class ComboboxItem
{
public object Value{get;set;}
public string Text {get;set;}
public override string ToString(){ return Text; }
}
Then, you can do this:
var item = new CombobxItem { Value = 123, Text = "Some text" };
combobox1.Items.Add(item);
you dont need to add .Text at the end of ("text","value")
so add it as :
comboBox1.Items.Add(new ComboBoxItem("dormir","12"));
You are on the right lines by creating your own ComboBoxItem class.
public class ComboboxItem
{
public string Text { get; set; }
public object Value { get; set; }
}
There are two ways to use this, (Constructor aside):
Method 1:
private void button1_Click(object sender, EventArgs e)
{
ComboboxItem item = new ComboboxItem();
item.Text = "Item text1";
item.Value = 12;
comboBox1.Items.Add(item);
}
Method 2:
private void button1_Click(object sender, EventArgs e)
{
ComboboxItem item = new ComboboxItem
{
Text = "Item text1",
Value = 12
};
comboBox1.Items.Add(item);
}
Have you tried adding it like this instead? Then when ever you get the Item out just cast it as a ComboboxItem :)
...
var selectedItem = comboBox1.SelectedItem as ComboboxItem;
var myValue = selectedItem.Value;
...
Alternative KeyValuePair:
comboBox1.Items.Add(new KeyValuePair("Item1", "Item1 Value"));
Question based on returnign string value and other combobox answers..
ComboBox: Adding Text and Value to an Item (no Binding Source)

ListBox and object properties

Been looking for a clear example of this.
I made a new object including setting several properties, added the whole object to the listBox then wrote a string to describe them. Now I want one item from the lsitBox object at the selected index. There are many syntaxes that appear to have similar but different usages it is complicating the search...
Pseudocode:
SpecialClass object = new SpecialClass;
object.propertyA;
Object.PropertyB;
listBox.Items.Add(object);
//listBox.SelectedItem[get propertyA]? What would retrieve propertyA or propertyB from the //list after putting the object in the list?
.... I tried to use this variable setting, something like this...
MRecipeForm parent = new MRecipeForm();
ListViewItem item = new ListViewItem();
item.Tag = parent.recipeListB.Items;
var myObject = (double)parent.recipeListB.SelectedItems[0].Tag;
// here you can access your properties myObject.propertA etc...
....
This is my current code that throws an exception:
MRecipeForm parent = new MRecipeForm();
ListViewItem item = new ListViewItem();
item.Tag = parent.recipeListB.Items;
Substrate o = ((ListBox)sender).SelectedItem as Substrate;
double dryWtLbs = o.BatchDryWtLbs; //BatchDryWtLbs is type double
Just store your object into your item's Tag property. When you adding your item:
ListViewItem item = new ListViewItem();
item.Tag = myObject;
...
Then:
var myObject = (SpecialClass)listBox.SelectedItems[0].Tag;
// here you can access your properties myObject.propertA etc...
Example to retrieve a double after changing selected index :
Forms 1 has a label : label1 and a listbox : listBox1
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
var object1 = new SpecialClass { Text = "First line", Number = 1d };
var object2 = new SpecialClass { Text = "Second line", Number = 2d };
listBox1.Items.Add(object1);
listBox1.Items.Add(object2);
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
SpecialClass o = ((ListBox)sender).SelectedItem as SpecialClass;
label1.Text = o.Number.ToString();
}
}
public class SpecialClass
{
public string Text { get; set; }
public double Number { get; set; }
public override string ToString()
{
return Text;
}
}

Select an item in a combobox and set the combobox text to a different one?

I want to make a ComboBox where the user can type an integer value into the text area, but the drop-down list contains several "defaults" values. For instance, the items in the drop-down list would be formatted like this:
Default - 0
Value 1 - 1
Value 2 - 2
What I want is that when the user selects an item (e.g. "Default - 0"), the ComboBox text will display only the number "0" rather than "Default - 0". The word "Default" is just informational text.
I have played with the following events: SelectedIndexChanged, SelectedValueChanged, and SelectionChangeCommitted, but I was not able to change the text of the ComboBox.
private void ModificationCombobox_SelectionChangeCommitted(object sender, EventArgs e)
{
ComboBox comboBox = (ComboBox)sender; // That cast must not fail.
if (comboBox.SelectedIndex != -1)
{
comboBox.Text = this.values[comboBox.SelectedItem.ToString()].ToString(); // Text is not updated after...
}
}
You can define a class for your ComboBox item, then create a List<ComboBoxItem> and use it as your Combobox.DataSource. With this you can set ComboBox.DisplayMember to a property you want displaying and still get reference to your object from ComboBox_SelectedIndexChanged():
class ComboboxItem
{
public int Value { get; set; }
public string Description { get; set; }
}
public partial class Form1 : Form
{
List<ComboboxItem> ComboBoxItems = new List<ComboboxItem>();
public Form1()
{
InitializeComponent();
ComboBoxItems.Add(new ComboboxItem() { Description = "Default = 0", Value = 0 });
ComboBoxItems.Add(new ComboboxItem() { Description = "Value 1 = 1", Value = 1 });
ComboBoxItems.Add(new ComboboxItem() { Description = "Value 2 = 2", Value = 2 });
comboBox1.DataSource = ComboBoxItems;
comboBox1.DisplayMember = "Value";
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
var item = (ComboboxItem)((ComboBox)sender).SelectedItem;
var test = string.Format("Description is \'{0}\', Value is \'{1}\'", item.Description, item.Value.ToString());
MessageBox.Show(test);
}
}
[edit]
If you want to change displayed text when box toogles between DropDown states try this: (this is a concept, not sure how that would behave)
private void comboBox1_DropDown(object sender, EventArgs e)
{
comboBox1.DisplayMember = "Description";
}
private void comboBox1_DropDownClosed(object sender, EventArgs e)
{
comboBox1.DisplayMember = "Value";
}

Categories