In my application, I have a model
public class LaborCategory
{
public int Id { get; set; }
[MaxLength(10)]
public string Code { get; set; }
[MaxLength(50)]
public string Name { get; set; }
public decimal Rate { get; set; }
public decimal OnSite { get; set; }
public decimal OffSite { get; set; }
}
I am wanting to create a comboBox (selectLaborCat) that has the first option as "Add New Labor Category" (this would be index 0) then the rest of the list where the selectLaborCat.Value = dataSet.Id and the selectLaborCat.Text = dataSet.Code
I THINK I am getting part of it correct by using
var categories = _context.LaborCategories.OrderBy(c => c.Code).ToArray();
selectLaborCat.DisplayMember = "Code";
selectLaborCat.ValueMember = "Id";
selectLaborCat.DataSource = categories;
as this renders the comboBox as I would expect.
But if I try a selectLaborCat.Items.Insert(0, "Add New Labor Category"); it errors out saying I cannot do Items collection cannot be modified when DataSource property is set
How can I get my "Add New Labor Category" in as index 0 ? I have tried adding the "Add New Category" in as a record in the data set, but I always want it to be index 0 of the comboBox, regardless of how I sort the dataset.
Am I forced to retrieve my dataset as a list, create a new list, add my default "Add New Category" as the first element, then copy the dataset list to the new list and bind the combo box to it like
var categories = _context.LaborCategories.OrderBy(c => c.Code).ToList();
var comboBoxElements = new List<LaborCategory>();
var laborCategory = new LaborCategory();
laborCategory.Id = 0;
laborCategory.Code = "Add New Labor Category";
comboBoxElements.Add(laborCategory);
foreach (var category in categories)
{
comboBoxElements.Add(category);
}
selectLaborCat.DisplayMember = "Code";
selectLaborCat.ValueMember = "Id";
selectLaborCat.DataSource = comboBoxElements;
or is there a better way?
comboBoxElements.Add(new LaborCategory { Id = 0, Code = "Add New Labor Category" });- Robert HarveyComboBoxto add items. - Reza Aghaei