473,385 Members | 2,013 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

ComboBox usage

I have a List of data objects.
I need to populate a ComboBox with the 'Description' field from the
objects.
I can do that with cmbBx.Items.Add( myObject.Description.ToString() );

myObject has 2 fields for example. id and description.

Later, I need to get the id of the selected item in the ComboBox...

In Delphi, I'd create a StringList, and add the ID to that, and then
just match up the index of the combobox with the corrasponding index
of the StringList to objtain the selected descriptions ID.

Is there a better way to do this in C#?

May 28 '07 #1
9 48317
On Mon, 28 May 2007 17:29:08 +0200, Cralis <ad***@myschoolmates.comwrote:
I have a List of data objects.
I need to populate a ComboBox with the 'Description' field from the
objects.
I can do that with cmbBx.Items.Add( myObject.Description.ToString() );

myObject has 2 fields for example. id and description.

Later, I need to get the id of the selected item in the ComboBox...

In Delphi, I'd create a StringList, and add the ID to that, and then
just match up the index of the combobox with the corrasponding index
of the StringList to objtain the selected descriptions ID.

Is there a better way to do this in C#?

Yes, just add the items as they are to the ComboBox
Then set the DisplayMember property of the ComboBox
And the ValueMember property

ComboBox.DisplayMember = "Description";
ComboBox.ValueMember = "Id";

You can then get the selected id by using ComboBox.SelectedValue
Or, in case ValueMember doesn't work, use

MyObject myObject = (MyObject)ComboBox.SelectedItem

--
Happy coding!
Morten Wennevik [C# MVP]
May 28 '07 #2
Sounds like exactly what I need. But it's not working. Am I doing it
wrong?

cmbModels.Items.Clear();

cmbModels.Items.Add("Show All");
cmbModels.Items.Add("Not Model Specific");

cmbModels.DisplayMember = "description";
cmbModels.ValueMember = "id";

List<IModelmodels = doModels.getListOfModels(false);

foreach (IModel model in models)
{
cmbModels.Items.Add(model);
}
cmbModels.SelectedIndex = 0;

May 28 '07 #3
On Mon, 28 May 2007 19:25:25 +0200, Cralis <ad***@myschoolmates.comwrote:
Sounds like exactly what I need. But it's not working. Am I doing it
wrong?

cmbModels.Items.Clear();

cmbModels.Items.Add("Show All");
cmbModels.Items.Add("Not Model Specific");

cmbModels.DisplayMember = "description";
cmbModels.ValueMember = "id";

List<IModelmodels = doModels.getListOfModels(false);

foreach (IModel model in models)
{
cmbModels.Items.Add(model);
}
cmbModels.SelectedIndex = 0;

Well, you are adding a mix of objects. You need to create IModel objects with description "Show All" and "Not Model Specific". You can then use the DataSource property as well

private void Method()
{
cmbModels.Items.Clear();

List<IModelmodels = new List<IModel>();
models.Add(new Model("Show All"));
models.Add(new Model("Not Model Specific"));
models.AddRange(doModels.getListOfModels(false));

cmbModels.DataSource = models;
cmbModels.DisplayMember = "Description";
cmbModels.ValueMember = "Id";
}

public interface IModel
{
string Description { get; set;}
int Id { get;set;}
}

public class Model : IModel
{
string description;
int id;
public string Description { get { return description; } set{ description = value; } }
public int Id { get { return id; } set { id = value; } }
public Model(string description)
{
this.Description = description;
}
}

However, using a DataSource, you may not be able to specify the selectedindex at the time you set the DataSource, but as the default index is 0 anyway you won't need to set it at all. The IModel and Model objects are added for comparison. Note the capitalization of the Description and Id properties. Properties should always start with a capital letter.

--
Happy coding!
Morten Wennevik [C# MVP]
May 28 '07 #4
On Mon, 28 May 2007 10:25:25 -0700, Cralis <ad***@myschoolmates.comwrote:
Sounds like exactly what I need. But it's not working. Am I doing it
wrong?
It's hard to say whether you're doing it wrong, given that you didn't post
all of the code.

But it appears you have the correct general idea. Do make sure that
IModel has the properties you've assigned, of course, named exactly as the
strings you assign to the ComboBox properties..

Pete
May 28 '07 #5
I have this:

public interface IModel
{
int id { get; set;}
string description { get;}
bool deleted { get; set;}
string manufacturer { get; set;}
string model { get; set;}
string edition { get; set;}
}

So it does seem my interface is OK. My part object does have : IPart.

I'm confused how you can do this:
models.Add(new Model("Show All"));
models.Add(new Model("Not Model Specific"));

How would it allow that? And if you can do this, can you not assign a
hard coded ID?

May 28 '07 #6
To add to that, the ComboBox is being populated, and visually, is
correct. But then I select an item, I am saying:

private void PopulateList()
{
lvParts.Items.Clear();
List<IPartparts;

if (cmbModels.SelectedIndex < 1) // Not the first 2 items
{
parts = doParts.GetListOfParts();
}
else
{
parts =
doParts.GetListOfParts(Convert.ToInt32(cmbModels.S electedValue.ToString())); //
ERROR
}

On the line marked as //ERROR, it says: Object reference not set to
instance of an object.

Not sure why.

May 28 '07 #7
On Mon, 28 May 2007 13:30:45 -0700, Cralis <ad***@myschoolmates.comwrote:
[...]
On the line marked as //ERROR, it says: Object reference not set to
instance of an object.

Not sure why.
You should debug it. You may find it useful to break that line into a
sequence of lines using local variables, so that it is easier to look at
each evaluation that occurs.

Obviously at some point you are trying to do something when something else
has returned null. I suspect SelectedValue is returning the null, but
there's no way to know for sure. You, however, have access to the code
and a debugger (I assume). It should not be difficult to find out what's
wrong.

I also agree with Morten that you should figure out a way to have "dummy"
IModel instances that correspond to "Show All" and "Not Model Specific".
Again, you are in the best position to determine how to do that.

Pete
May 28 '07 #8
GS
I was playing around with enum for a little while. I end up using Alex
Kolesnichenko, 2005 HumanReadable Attribute.cs form chap project
one caveat when you set the combobox box to his arraylist of
HumanReadablePair
you should also set
the displayMember to "HumanReadableName"
for example

in form_load
I have
ResourceManager resources =
new ResourceManager("RegexParse.Strings",
Assembly.GetExecutingAssembly()); // "RegexParse" is my namespace for the
project

// Get human-readable enum values
ArrayList regexCategories =

EnumToHumanReadableConverter.Convert(typeof(regexC ategory), resources);
// note regexCategory is a **public** enum type iwthin the
class

// Bind controls to data
comboBoxRegexCategory.DataSource = (ICollection)regexCategories;
comboBoxRegexCategory.DisplayMember = "HumanReadableName";
comboBoxRegexCategory.SelectedItem = regexCategory.eSimple;

I don't pretend to understand why I need public scope for the enum to work
but it worked for me

I don't need coding classes per enum combo but I do have to either use
attributs on enum or enter the relevant info in Strings.resx
good luck

ref: Humanizing the Enumerations - The Code Project - C# Programming
you could even compile the HumanReadableAttribute.cs into a dll and shared
among your projects if you wish

"Cralis" <ad***@myschoolmates.comwrote in message
news:11**********************@w5g2000hsg.googlegro ups.com...
I have a List of data objects.
I need to populate a ComboBox with the 'Description' field from the
objects.
I can do that with cmbBx.Items.Add( myObject.Description.ToString() );

myObject has 2 fields for example. id and description.

Later, I need to get the id of the selected item in the ComboBox...

In Delphi, I'd create a StringList, and add the ID to that, and then
just match up the index of the combobox with the corrasponding index
of the StringList to objtain the selected descriptions ID.

Is there a better way to do this in C#?

May 29 '07 #9


On Mon, 28 May 2007 22:30:45 +0200, Cralis <ad***@myschoolmates.comwrote:
To add to that, the ComboBox is being populated, and visually, is
correct. But then I select an item, I am saying:

private void PopulateList()
{
lvParts.Items.Clear();
List<IPartparts;

if (cmbModels.SelectedIndex < 1) // Not the first 2 items
{
parts = doParts.GetListOfParts();
}
else
{
parts =
doParts.GetListOfParts(Convert.ToInt32(cmbModels.S electedValue.ToString())); //
ERROR
}

On the line marked as //ERROR, it says: Object reference not set to
instance of an object.

Not sure why.

Cralis, did you read my reply? You are adding a mix of objects. Although the IModel objects do have the specified properties, a String object does not. You can't have different objects in the list if you want to use DisplayMember/ValueMember. Since the string object's description andid properties cannot be resolved, the ValueMember is ignored and all objects are displayed using object.ToString(). If you insist on mixing objects, then you need to use SelectedItem and cast the returned object toits proper type.

--
Happy coding!
Morten Wennevik [C# MVP]
May 29 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Ed From NY | last post by:
I have a combobox that is loaded with last name from a table. I want to click on the persons last name, and have all the ADO.NET bound textboxes on a form load with the clicked persons data. I can...
7
by: Malcolm Cook | last post by:
Hi, I've created and installed a custom UDF to populate my combobox, and have defined it per :...
1
by: Stephen.Hunter | last post by:
Hello Everybody (anybody)? I am trying to appent a combobox to include data entered by a user which is Not In List. I have came accross this code from Allen Browne which seems to be what I am...
3
by: Lubomir | last post by:
Hi, I have a combobox and datagrid in a form. When an Item is selected from a combobox, a method is called, which will make selection from a database according selected item and populate...
9
by: Steffen Laser | last post by:
Hi group, I have a problem that I already have posted to the german C# newsgroup. Since nobody could help me there, I'd like to try it here again: I set the selected item of a combobox like...
3
by: barry | last post by:
hi i have a screen with customer details on it. for some items i only want to make a combobox available. eg. country - this will hold a defined list of countries. my question is how i set up the...
2
by: trevor.niemack | last post by:
Hello I want to have a combobox that saves all the input, so if I put the word test in the combobox and submit a query I want to have test saved so that the next time I go to that combobox I can...
3
by: Nofi | last post by:
Hello, I'm trying to fill my combobox per code, not with a DataSet because I want to have an empty row in it and this wasn't possible when working with a DataSet. The fill works fine, but when I...
19
by: active | last post by:
I'm using a ComboBox to display objects of a class I've defined, say CQQ. Works great except somehow I occasionally set an Item to a String object instead of an object of type CQQ. It looks...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.