Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add an item to combobox before binding data from the database

I had a combobox in a Windows Forms form which retrieves data from a database. I did this well, but I want to add first item <-Please select Category-> before the data from the database. How can I do that? And where can I put it?

public Category()
{
    InitializeComponent();
    CategoryParent();

}

private void CategoryParent()
{
    using (SqlConnection Con = GetConnection())
    {
        SqlDataAdapter da = new SqlDataAdapter("Select Category.Category, Category.Id from Category", Con);
        DataTable dt = new DataTable();
        da.Fill(dt);
        CBParent.DataSource = dt;
        CBParent.DisplayMember = "Category";
        CBParent.ValueMember = "Id";
    }
}
like image 926
Myworld Avatar asked Feb 27 '11 15:02

Myworld


People also ask

What is the correct way to add new item to ComboBox?

To add items to a ComboBox, select the ComboBox control and go to the properties window for the properties of this control. Click the ellipses (...) button next to the Items property. This opens the String Collection Editor dialog box, where you can enter the values one at a line.

What is DisplayMember and ValueMember in C#?

DisplayMember : To display the underlying datasource for Windows Forms ComboBox. ValueMember : To use as the actual value for the items.


2 Answers

You could either add the default text to the Text property of the combobox like this (preferred):

CBParent.Text = "<-Please select Category->";

Or, you could add the value to the datatable directly:

da.Fill(dt);
DataRow row = dt.NewRow();
row["Category"] = "<-Please select Category->";
dt.Rows.InsertAt(row, 0);
CBParent.DataSource = dt;
like image 166
Forgotten Semicolon Avatar answered Oct 08 '22 13:10

Forgotten Semicolon


public class ComboboxItem
{
    public object ID { get; set; }
    public string Name { get; set; }

}

public static List<ComboboxItem> getReligions()
{
    try
    {
        List<ComboboxItem> Ilist = new List<ComboboxItem>();
        var query = from c in service.Religions.ToList() select c;
        foreach (var q in query)
        {
            ComboboxItem item = new ComboboxItem();
            item.ID = q.Id;
            item.Name = q.Name;
            Ilist.Add(item);
        }
        ComboboxItem itemSelect = new ComboboxItem();
        itemSelect.ID = "0";
        itemSelect.Name = "<Select Religion>";
        Ilist.Insert(0, itemSelect);
        return Ilist;
    }
    catch (Exception ex)
    {
        return null;
    }    
}

ddlcombobox.datasourec = getReligions();
like image 35
owolabi opeyemi jeleel Avatar answered Oct 08 '22 14:10

owolabi opeyemi jeleel