disasterkid
disasterkid

Reputation: 7278

First combobox item missing after combobox filled with datatable

I have a combobox on my form and a datatable. The combobox will be filled by some row values fro the datatable. But before that I would like to add a combobox item called (new) that will be the first option of the combobox in case the user would like to add a new item.

But when my combobox is filled, my (new) does not show up for some reason.

string query = "SELECT Id,Name,Text FROM ApsisSms ORDER BY Id DESC";
OleDbDataAdapter da = new OleDbDataAdapter(query, conn);
conn.Open();
da.Fill(dtSmsMessages);
comboSMSMessages.Items.Add(new ComboboxItem() { Text = "(new)", Value = "-1" });
if (dtSmsMessages.Rows != null && dtSmsMessages.Rows.Count > 0)
{
    comboSMSMessages.Items.Clear();

    for (int i = 0; i < dtSmsMessages.Rows.Count; i++)
    {
        ComboboxItem item = new ComboboxItem()
        {
            Text = dtSmsMessages.Rows[i]["Name"].ToString(),
            Value = dtSmsMessages.Rows[i]["Id"].ToString()
        };
        comboSMSMessages.Items.Add(item);
    }
}
comboSMSMessages.SelectedIndex = 0;

Upvotes: 0

Views: 267

Answers (1)

Code4U
Code4U

Reputation: 113

comboSMSMessages.Items.Clear(); Clear all the items Add comboSMSMessages.Items.Add(new ComboboxItem() { Text = "(new)", Value = "-1" }); after you cleared the combobox Your code should be like

string query = "SELECT Id,Name,Text FROM ApsisSms ORDER BY Id DESC";
OleDbDataAdapter da = new OleDbDataAdapter(query, conn);
conn.Open();
da.Fill(dtSmsMessages);

if (dtSmsMessages.Rows != null && dtSmsMessages.Rows.Count > 0)
{
comboSMSMessages.Items.Clear();

comboSMSMessages.Items.Add(new ComboboxItem() { Text = "(new)", Value = "-1" });
for (int i = 0; i < dtSmsMessages.Rows.Count; i++)
{
 ComboboxItem item = new ComboboxItem()
    {
        Text = dtSmsMessages.Rows[i]["Name"].ToString(),
        Value = dtSmsMessages.Rows[i]["Id"].ToString()
    };
    comboSMSMessages.Items.Add(item);
 }
}
comboSMSMessages.SelectedIndex = -1;

Upvotes: 2

Related Questions