开发者

Adding Data to a ComboBox (Not bound data)

I wish to add data to a comboboxlist but am unsure of the correct method in which to do this. The data comes from a raw SQL statement.

I have looked at the binding data directly from the database but it is not clear how all this binding and datasets work for me so I have decided to skip this and insert the data to the combox myself (with your help).

The code i have see online goes like the following:

public partial class Form1 : Form {
    // Content item for the combo box
    private class Item {
        public string Name;
        public int Value;
        public Item(string name, int value) {
            Name = name; Value = value;
        }
        public override string ToString() {
            // Generates the text shown in the combo box
            return Name;
        }
    }
    public Form1() {
        InitializeComponent();
        // Put some stuff in the combo box
        comboBox1.Items.Add(new Item("Blue", 1));
        comboBox1.Items.Add(new Item("Red", 2));
        comboBox1.Items.Add(new Item("Nobugz", 666));
    }

    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) {
        // Display the Value property
        Item itm = (Item)comboBox1.Sele开发者_如何学编程ctedItem;
        Console.WriteLine("{0}, {1}", itm.Name, itm.Value);
    }
}

Do you really have to create a new class to just to add data to a combobox ? Also, using the above technique my code looks like:

    while (rdata.Read()){
        String Name = (String)rdata["vetName"];
        Name = Name.Trim();
        String Surname = (String)rdata["vetSurname"];
        Surname = Surname.Trim();

        String id = rdata["vetID"].ToString().Trim();

        MessageBox.Show("ID " + id);

        int value1 = Convert.ToInt32(id);
        MessageBox.Show("value1 " + value1);

        String display = (String)Name + " " + Surname;

        editVetComboBox.Items.Add(new Item(display, 2));
    }

The problem is that while the combobox is populated with firstname and surname the value (ID) is not added.

Any Ideas ?

Many Thanks, Richard


SOURCE: http://tipsntricksbd.blogspot.com/2007/12/combobox-is-one-of-most-common-gui.html

ComboBox is one of the most common GUI elements. It is used to provide the user the facility of selecting an item from a list or enter a new text. Here I’ll show you some common and useful functionalities of ComboBox in C# using Microsoft Visual Studio .Net 2005.

Simplest ComboBox:

In the simplest case, we add some strings in the list like the following-

myComboBox.Items.Add("Bangladesh");
myComboBox.Items.Add("India");
myComboBox.Items.Add("Pakistan");
myComboBox.Items.Add("Srilanka");
myComboBox.Items.Add("Maldives");
myComboBox.Items.Add("Nepal");
myComboBox.Items.Add("Bhutan");

Sorted List:

Generally users expect that the options will be shown in sorted order. For this purpose, we have to add one line of code-

myComboBox.Sorted = true;

DropDownStyle:

In ComboBox, the user can either enter a text or just select an item from the list. So the developer should set its style. There are 3 options available:

ComboBoxStyle.DropDownList: User can just select one item from a list.
ComboBoxStyle.DropDown: User can either type a text or select an item from list.
ComboBoxStyle.Simple: User can only type a text in text box. Item list is not shown.

Example:

myComboBox.DropDownStyle = ComboBoxStyle.DropDown;

Suggesstion/Dictionary:

When a user enters a text, he/she becomes happy if some suggestions are shown just below the combo box at the time of typing. For this functionality, we need to write couple of lines-

myComboBox.AutoCompleteSource = AutoCompleteSource.ListItems;
myComboBox.AutoCompleteMode = AutoCompleteMode.Suggest;

A Trick:

There may be a case where user selects some readable text, but for the programmer corresponding value (not the selected text) is important. For example, in database project StudentID is more important for a programmer than StudentName. So, it would be nice if we could add (Name, Value) combination in combo box and at the time of Name selection we could easily get the corresponding value.

We can do it by adding an object containing Name and Value.

class ComboBoxItem
{
public string Name;
public int Value;
public ComboBoxItem(string Name, int Value)
{
this.Name = Name;
this.Value = Value;
}
}


myComboBox.Items.Add(new ComboBoxItem("Ashis Saha",1));
myComboBox.Items.Add(new ComboBoxItem("Subrata Roy", 2));
myComboBox.Items.Add(new ComboBoxItem("Aminul Islam", 3));
myComboBox.Items.Add(new ComboBoxItem("Shakibul Alam", 4));
myComboBox.Items.Add(new ComboBoxItem("Tanvir Ahmed", 5));

But if you now see the list of ComboBox, you will notice that all items are same and they are the class names of those objects. In fact, the items are nothing but the output of the ToString() function of those objects. So if we simply override the ToString() function to behave as our expectation, we are done.

class ComboBoxItem
{
public string Name;
public int Value;
public ComboBoxItem(string Name, int Value)
{
this.Name = Name;
this.Value = Value;
}

// override ToString() function
public override string ToString()
{
return this.Name;
}
}

You can get the selected value in following way-

int selectedValue = ((ComboBoxItem)myComboBox.SelectedItem).Value;


I can see that value is always 2 in your code. This might be the issue that you have.

Also, tried to simplify your code a little:

while (rdata.Read())
{
    string name = (string)rdata["vetName"];
    string surname = (string)rdata["vetSurname"];
    int id = (int)rdata["vetID"];
    string display = name.Trim() + " " + surname.Trim();
    editVetComboBox.Items.Add(new Item(display, id));
}

Assuming vetID is integer and all the listed fields are not nullable in database.


No, you don't have to create a new class to add data to a ComboBox, you can just add strings if you want. Classes are for convenience, and they certainly seem convenient here - why would you want to avoid them? (Maybe I don't quite understand your question...)

If all you're going to be doing is performing string operations and using ToString() on the class all the time, not accessing the individual properties, there's no point in having it then - just format it into a string and use that.


No, you don't have to create your own class...but it does make sense with what you are doing. In your application, it is a good idea to have a class type represent your database entity. Override the ToString() method of your entity class. Next, insert these class types directly into the ComboBox. The ComboBox will call ToString() on your entity to display the text.

Here is what it would look like:

public class Vet
{
    public int ID { get; set; }
    public string Name { get; set; }
    public string SurName { get; set; }

    public Vet()
    {
        // default constructor
    }

    public Vet( IDataRecord record )
    {
        ID = (int) record["vetid"];
        Name = (string) record["vetname"];
        SurName = (string) record["vetsurname"];
    }

    public override string ToString()
    {
        return Name + " " + SurName;
    }
}

Next, add the instances directly to your combo box:

comboBox.Items.Clear();
while( rdata.Read() )
{
   comboBox.Items.Add( new Vet( rdata ) );
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜