c# ComboBox, save item with value and text - c#

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)

Related

variable and textbox mapping in c# without using textbox changed event

I'm trying a code which changes the TextBox values when variable mapped with it changes accordingly without using TextBox changed event. I am not finding any clue to where to start please help me.
Here is the code:
public void varChange(TextBox text)
{
String name;
name="sachin";
text.Text = name;
MessageBox.Show("" + text.Text);
}
You can "extend" TextBox :
public class MeTextBox : TextBox
{
public override string Text
{
get
{
return base.Text;
}
set
{
//base.Text = value; // use it or not .. whatever
MyTextWasChanged();
}
}
void MyTextWasChanged()
{
String name;
name="sachin";
//text.Text = name;
base.Text = name;
MessageBox.Show("" + text.Text);
}
}
If that's not what you're looking for then give some more details and I'll update this answer.
You can use a BindingSource
public partial class Form1 : Form
{
private System.Windows.Forms.BindingSource form1BindingSource;
public string BindedProp { get; set; } //Variable or property binded with TextBox
public Form1()
{
InitializeComponent();
this.form1BindingSource = new System.Windows.Forms.BindingSource(new System.ComponentModel.Container());
this.form1BindingSource.DataSource = typeof(binding.Form1);
this.textBox.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.form1BindingSource, "BindedProp", true));
this.form1BindingSource.DataSource = this;
}
//add a button control to assing value code event click
private void btAssingValueProperty_Click(object sender, EventArgs e)
{
BindedProp = "Value assigned";
form1BindingSource.ResetBindings(false);
}
//add a other button control to show value code event click
private void btShowValueProperty_Click(object sender, EventArgs e)
{
MessageBox.Show(BindedProp);
}
}

Loaded an object into a listbox with 2 variables, listbox show only the name

I have a Class where there a 2 variables int ID and string name. I made a list of several objects and loaded them onto a listbox. The listbox only show the name. Is there a way to retrieve the ID from the listbox?
class Show
{
private int _Id;
private string _Naam;
private string _Genre;
public override string ToString()
{
return Naam;
}
}
from a database i make a list of objects.
private void bttn_zoek_Click(object sender, EventArgs e)
{
foreach (object a in List<show> List)
{
listbox1.Items.Add(a);
}
}
I hope this is enough
Assuming WinForms, here is a super simple example of overriding ToString() to control how the class is displayed in the ListBox, and also how to cast the selected item in the ListBox back to your class type so you can extract values from it. There are other ways to accomplish this task, but you should understand a bare bones example like this first:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
SomeClassName sc1 = new SomeClassName();
sc1.ID = 411;
sc1.Name = "Information";
listBox1.Items.Add(sc1);
SomeClassName sc2 = new SomeClassName();
sc2.ID = 911;
sc2.Name = "Emergency";
listBox1.Items.Add(sc2);
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (listBox1.SelectedIndex != -1)
{
SomeClassName sc = (SomeClassName)listBox1.Items[listBox1.SelectedIndex];
label1.Text = "ID: " + sc.ID.ToString();
label2.Text = "Name: " + sc.Name;
}
}
}
public class SomeClassName
{
public int ID;
public string Name;
public override string ToString()
{
return ID.ToString() + ": " + Name;
}
}
Posting some of your code would be nice. Have you tried listBox.items[index].ID?
Here I'm assuming that index is whatever index you're currently searching for.
You can also try listBox.SelectedItem[index].ID if you're doing something like an event.

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;
}
}

Set ComboBox Text on Basis of SelectedIndex

I am trying to set the Text property of ComboBox on the basis of SelectedIndex but the problem is Text is becoming String.Empty after changing the Index of Combobox.
Each Item in ComboBox correspond to a string in DataTable having 2 columns Name, Description
What i need is when users select's a Name (Index Changes) when i want to show the Description of that in ComboBox
What i have tried :
private void tbTag_SelectionChangeCommitted(object sender, EventArgs e)
{
// get the data for the selected index
TagRecord tag = tbTag.SelectedItem as TagRecord;
// after getting the data reset the index
tbTag.SelectedIndex = -1;
// after resetting the index, change the text
tbTag.Text = tag.TagData;
}
How i have populated the Combobox
//load the tag list
DataTable tags = TagManager.Tags;
foreach (DataRow row in tags.Rows)
{
TagRecord tag = new TagRecord((string)row["name"], (string)row["tag"]);
tbTag.Items.Add(tag);
}
Helper Class Used :
private class TagRecord
{
public TagRecord(string tagName, string tagData)
{
this.TagName = tagName;
this.TagData = tagData;
}
public string TagName { get; set; }
public string TagData { get; set; }
public override string ToString()
{
return TagName;
}
}
I think that happens because -1 index in ComboBox means that no item was selected (msdn) and you are trying to change text of it. I would create one more element (at index 0) and make it change text depending on selection:
bool newTagCreated = false;
private void tbTag_SelectionChangeCommitted(object sender, EventArgs e)
{
TagRecord tag = tbTag.SelectedItem as TagRecord;
TagRecord newtag = null;
if (!newTagCreated)
{
newtag = new TagRecord(tag.TagData, tag.TagName); //here we change what is going to be displayed
tbTag.Items.Insert(0, newtag);
newTagCreated = true;
}
else
{
newtag = tbTag.Items[0] as TagRecord;
newtag.TagName = tag.TagData;
}
tbTag.SelectedIndex = 0;
}
Found a solution.
private void tbTag_SelectedIndexChanged(object sender, EventArgs e)
{
TagRecord tag = tbTag.SelectedItem as TagRecord;
BeginInvoke(new Action(() => tbTag.Text = tag.TagData));
}

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