Set a default value in a combobox from enum - c#

I have a combobox that I have some values in from an enum.
I want a default value to show on the combobox when the program start.. but I cant get it to work..
This is what I have tried so far in my MainForm:
cmbPrio.Items.AddRange(Enum.GetNames(typeof(PriorityType.Prioritytypes)));
cmbPrio.SelectedValue = PriorityType.Prioritytypes.Normal;
this is the class with the enum:
class PriorityType
{
public enum Prioritytypes
{
Very_Important,
Important,
Normal,
Less_Importan
}
}

You are populating the names into the combo, which is just a collection of string, which means that values you use to set must also be strings.
cmbPrio.SelectedValue = Enum.GetName(typeof(PriorityType.Prioritytypes), PriorityType.Prioritytypes.Normal);

Why don't you simply set the Index? :
cmbPrio.SelectedIndex = 0;

Another alternative would be to set the ComboBox items to:
cmbPrio.Items.AddRange(Enum.GetValues(typeof(PriorityType.PriorityTypes))
.Cast<PriorityType.PriorityTypes>());
cmbPrio.SelectedValue = PriorityType.PriorityTypes.Normal;
This allows you to treat the selected values as actual PriorityType.PriorityTypes as opposed to strings.

Related

Values appear as the class name in the listbox

I'm reading in a field from a database into a list, like so
PaceCalculator pace = new PaceCalculator();
List<PaceCalculator> Distancelist = new List<PaceCalculator>();
while (Reader.Read()) //Loops through the database and adds the values in EventDistance to the list
{
pace.Distance = (int)Reader["EventDistance"];
Distancelist.Add(pace);
}
I want to put the values into a listbox, but when I do it like this:
listBox1.DataSource = Distancelist;
It only shows the class name, which is PaceCalculator. It shows the right number of values, it just shows the class name instead. I want to see the integers in there.
You have two options,
Override ToString in your class to return the required string
or, if you only want to display Distance then specify that as DisplayMember
like:
listBox1.DisplayMember = "Distance";
listBox1.DataSource = Distancelist;
This will display you the Distance element from your list. Or you can override ToString in your class PaceCalculator like:
public override string ToString()
{
return string.Format("{0},{1},{2}", property1, property2, property3);
}
EDIT:
Based on your comment and looking at your code, You are doing one thing wrong.
this only displays the last value in the list, 46, 8 times
You are adding the same instance (pace) of your class in your list on each iteration. Thus it is holding the last value (46). You need to instantiate a new object in the iteration like:
while (Reader.Read())
{
PaceCalculator pace = new PaceCalculator();
pace.Distance = (int)Reader["EventDistance"];
Distancelist.Add(pace);
}
Specify the property of PaceCalculator to display.
listBox1.DataSource = Distancelist;
listBox1.DisplayMember = "Distance";
The ListBox control allows you to pick a property from the collection to display to the user.
There's also a ValueMember property that allows you to specify the value for each item in the ListBox. Assuming your data included an id called "SomeUniqueRecordId", for instance:
listBox1.ValueMember = "SomeUniqueRecordId";

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;

Listbox.DisplayMember won't display value from calculated property

I'm using SubSonic 2.2 for my DAL and extended one of my classes with a calculated property that returns a string containing another property with indenting based on the level of the outline at which the item occurs. The code for the property is below. The problem is that when I try to use this property as the DisplayMember for a ListBox control on a form (the reason I wrote it in the first place) it won't work. The ListBox reverts to displaying the ID property which is set as the ValueMember. To test that the property was working I looped through the collection of objects that I was populating the ListBox with and, using MessageBox.Show(obj.property), confirmed that it was indeed returning the value I'm looking for. Am I missing something or should this work? btw - There may be a better way to do the indenting but that's not what I'm after at the moment, thanks!
Code follows:
public partial class InteriorsCategory : ActiveRecord, IActiveRecord
{
public string ListDisplay
{
get
{
string returnValue = "";
for (int i = 1; i < this.SpecLevel; i++)
{
returnValue += " ";
}
returnValue += this.CategoryName;
return returnValue;
}
}
}
<>
I definitely get data in my collection and the binding I'm doing is exactly the same as yours (binding code posted below). The return value of the ListDisplay property that I'm using is a string concatenation of two values in the object. Think of it as a "full name" property that concatenates the FirstName a space and the LastName properties into a single string which it returns. I am trying to bind the ListDisplay property to the DisplayMember property of the listbox, but all that shows in the listbox is the Id field which I am binding to the ValueMember.
private void FillCategories()
{
lstPackageCategories.DataSource = new InteriorsCategoryCollection().Load();
lstPackageCategories.DisplayMember = "CategoryName";
lstPackageCategories.ValueMember = "Id";
((InteriorsCategoryCollection)(lstPackageCategories.DataSource)).Sort("SpecSection", true);
lstPackageCategories.SelectedItem = lstPackageCategories.Items[0];
currentCategory = (InteriorsCategory)lstPackageCategories.SelectedItem;
RefreshAvailableItems();
}
If your able to see your data in the collection, then it sounds like there is a problem on the binding of your ListBox. Here is an example of how I bind a ListBox using a SubSonic collection of values.
ISOCountryCodeCollection countrys =
new ISOCountryCodeCollection().OrderByAsc(ISOCountryCode.Columns.Country).Load();
Country.DataSource = countrys;
Country.DataValueField = "ThreeChar";
Country.DataTextField = "Country";
Country.DataBind();
In the example above, I'm binding the 3 character country code to the "DataValueField" and the full country name to the "DataTextField".

How can I add an item to a ListBox in C# and WinForms?

I'm having trouble figuring out how to add items to a ListBox in WinForms.
I have tried:
list.DisplayMember = "clan";
list.ValueMember = sifOsoba;
How can I add ValueMember to the list with an int value and some text for the DisplayMember?
list.Items.add(?)
Btw. I can't use ListBoxItem for any reasons.
ListBoxItem is a WPF class, NOT a WinForms class.
For WPF, use ListBoxItem.
For WinForms, the item is a Object type, so use one of these:
1. Provide your own ToString() method for the Object type.
2. Use databinding with DisplayMemeber and ValueMember (see Kelsey's answer)
list.Items.add(new ListBoxItem("name", "value"));
The internal (default) data structure of the ListBox is the ListBoxItem.
In WinForms, ValueMember and DisplayMember are used when data-binding the list. If you're not data-binding, then you can add any arbitrary object as a ListItem.
The catch to that is that, in order to display the item, ToString() will be called on it. Thus, it is highly recommended that you only add objects to the ListBox where calling ToString() will result in meaningful output.
You might want to checkout this SO question:
C# - WinForms - What is the proper way to load up a ListBox?
DisplayMember and ValueMember are mostly only useful if you're databinding to objects that have those properties defined. You would then need to add an instance of that object.
e.g.:
public class MyObject
{
public string clan { get; set; }
public int sifOsoba { get; set; }
public MyObject(string aClan, int aSif0soba)
{
this.clan = aClan;
this.sif0soba = aSif0soba;
}
public override string ToString() { return this.clan; }
}
....
list.Items.Add(new MyObject("hello", 5));
If you're binding it manually then you can use the example provided by goggles
The way I do this - using the format Event
MyClass c = new MyClass();
listBox1.Items.Add(c);
private void listBox1_Format(object sender, ListControlConvertEventArgs e)
{
if(e.ListItem is MyClass)
{
e.Value = ((MyClass)e.ListItem).ToString();
}
else
{
e.Value = "Unknown item added";
}
}
e.Value being the Display Text
Then you can attempt to cast the SelectedItem to MyClass to get access to anything you had in there.
Also note, you can use anything (that inherits from object anyway(which is pretty much everything)) in the Items Collection.
If you just want to add a string to it, the simple answer is:
ListBox.Items.Add("some text");
You have to create an item of type ListBoxItem and add that to the Items collection:
list.Items.add( new ListBoxItem("clan", "sifOsoba"));
If you are adding integers, as you say in your question, this will add 50 (from 1 to 50):
for (int x = 1; x <= 50; x++)
{
list.Items.Add(x);
}
You do not need to set DisplayMember and ValueMember unless you are adding objects that have specific properties that you want to display to the user. In your example:
listbox1.Items.Add(new { clan = "Foo", sifOsoba = 1234 });

Get the combobox text in C#

I filled up a combobox with the values from an Enum.
Now a combobox is text right? So I'm using a getter and a setter. I'm having problems reading the text.
Here's the code:
public BookType type
{
get
{
return (BookType)Enum.Parse(typeof(BookType), this.typeComboBox.Text);
}
set
{
this.typeComboBox.Text = value.ToString();
}
}
For some reason, this.typeComboBox.Text always returns an empty string when I select an item on the combobox.
Does someone see what I'm doing wrong?
EDIT: I have come to the conclusion that the problem lies in timing.
The point in time at which I summon the text is indeed after I changed the combobox, but still before that value is parsed as a value.
Problem fixed in a different way now, thanks for all the ideas.
string selectedText = this.ComboBox.GetItemText(this.ComboBox.SelectedItem);
The GetItemText method analyzes the item and returns the text of the bound to that item.
Set the DropDownStyle of the ComboBox to DropDownList. This will ensure that only the elements already in the list can be selected (no need to check that the text actually is a valid value).
Then if you use Enum.GetValues(typeof(BookType)) to fill the combobox then typeComboBox.SelectedItem property will be a value of BookType. So you can use this in the property getter and setter.
So to summarize. You don't have to bind the combobox to a list of text values as long as you use the DropDownList style. Use the SelectedItem property to get an item of the wanted type instead of checking the Text property.
Edit: You may have to check the SelectedItem property for null
The combobox starts at index -1, which has no text, thus an empty string: ""
I then change the index to a BookType that I need and then I get the wrong output...
Have you tried using this.typeComboBox.SelectedText instead of typeComboBox.Text ?
this.typeComboBox.SelectedItem.ToString()
I just created a simple windows form, and everything worked okay for me. Here is the code.
public enum Test
{
One, Two, Three
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.comboBox1.DataSource = Enum.GetNames(typeof(Test));
}
public Test Test
{
get
{
return (Test)Enum.Parse(typeof(Test), this.comboBox1.Text);
}
set
{
this.comboBox1.Text = value.ToString();
}
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show(this.Test.ToString());
this.Test = Test.Two;
MessageBox.Show(this.Test.ToString());
}
}

Categories

Resources