Click here to Skip to main content
15,886,518 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
Hi all,

I have a combobox binded with items.
I want to insert an item to be displayed first to tell the user to choose an item

var type = from m_types in DB.Types
           select m_types;

combobox.ValueMember = "Id";
combobox.DisplayMember = "Name";
combobox.DataSource = type;


I tried this but it return an error that a binded combobox can't be modified

combobox.Items.Insert(0, "Please choose an item");


Please is there a way to insert this item?

Thanks in advance.


Best regards,
Michael Waguih
:)
Posted
Updated 20-Aug-13 22:18pm
v3
Comments
Sergey Alexandrovich Kryukov 13-Aug-13 18:08pm    
ComboBox? Which one? Exact full type name, please.
—SA

 
Share this answer
 
You have to add the item to the datasource you bound the Combo to. Once you bind data to the Combo, you cannot use the Combo's own Items collection.
 
Share this answer
 
Comments
Michael Waguih 13-Aug-13 15:26pm    
How to add it with such code please ?
var type = from m_types in DB.Types
           select m_types;

DataTable dt_Types = new DataTable();
dt_Types.Columns.Add("t_ID", typeof(int));
dt_Types.Columns.Add("t_Name", typeof(string));
foreach (var t in type)
{
    dt_Types.Rows.Add(t.Id, t.Name);
}
DataRow dr = dt_Types.NewRow();
dr[0] = -1;
dr[1] = "Please choose an item";
dt_Types.Rows.InsertAt(dr, 0);
if (dt_Types.Rows.Count > 0)
{
    cbx_Types.DataSource = dt_Types;
    cbx_Types.DisplayMember = "t_Name";
    cbx_Types.ValueMember = "t_ID";
}
 
Share this answer
 
C#
 combobox.SelectedValuePath= "Id";
 combobox.DisplayMemberPath= "Name";
 combobox.ItemsSource= type;
combobox.Text="Please choose an item";
 
Share this answer
 
Comments
Michael Waguih 13-Aug-13 15:24pm    
I tried it and it didn't work
abbaspirmoradi 13-Aug-13 15:35pm    
U should create a class for type such this:
public class Type
{
public string Name { get; set; }

public string Id{ get; set; }

public Type(string name, string id)
{
Name= name;
Id= id;
}
}
Michael Waguih 13-Aug-13 15:37pm    
This class is already created I need to add an item to the selected data from this class
abbaspirmoradi 13-Aug-13 15:47pm    
Ok.You must have list of types.
List<type> Types=from m_types in DB.Types
select m_types;
Is this right?
Michael Waguih 13-Aug-13 15:49pm    
right and it's written in the question

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900