Agnieszka Polec
Agnieszka Polec

Reputation: 1511

c# comboxBox add default non selected text

I have a combobox and I fill it like this:

private void fillFarmAreaData()
{
    DataTable dt = new DataTable();
    dt.Columns.Add("ID", typeof(int));
    dt.Columns.Add("Description", typeof(string));
    farmArea.ValueMember = "ID";
    farmArea.DisplayMember = "Description";
    farmArea.SelectedValue = "ID";
    for (int i = 0; i < StaticData.FarmAreaNames.Count; i++) {
        dt.Rows.Add(StaticData.FarmAreaValues[i], StaticData.FarmAreaNames[i]);
    }
    farmArea.DataSource = dt;
}

where StaticData class is this:

static class  StaticData
{
    public static List<string> FarmAreaNames = new List<string>() { .... strings here};
    public static List<string> FarmAreaValues = new List<string>() { "1", "10", "11", "12", "13" };

}

The problem is that when I run the form, I already get the first value selected. what I want is to make the first option as this Select Area Name

What I have tried

I added Selected Area Name as the first string in the FarmAreaNames and added -1 as the first FarmAreaValue

and then when the user click save, I check the value, if it is -1 I show a validation error message.

However, I would like to know if windows form provides a better way for that.

thanks

Upvotes: 0

Views: 50

Answers (1)

Jai
Jai

Reputation: 269

try this after adding the data source for the Combobox control and finally insert an item to the specific position.

use

comboBox1.Items.Insert(0, "Select Area Name");

Upvotes: 1

Related Questions