user3138522
user3138522

Reputation: 111

Showing a selected value in combobox fetched from database

private void Form1_Load_1(object sender, EventArgs e)
{
    string Sql = "select status from lk_tb_project_status";

    OleDbConnection con = new OleDbConnection(constr);
    OleDbCommand com = new OleDbCommand(Sql, con);

    con.Open();

    OleDbDataReader DR = com.ExecuteReader();
    while (DR.Read())
    {
        comboBox1.Items.Add(DR[0]);
    }
}

I am fetching values from database and displaying in combobox(dropdownlist). There are two values in database that is sold and open. What I want is to change selected item on page load. Can anyone help me with this?

Upvotes: 0

Views: 2460

Answers (3)

Sudhakar Tillapudi
Sudhakar Tillapudi

Reputation: 26199

if you want to set first item as selecteditem.

Try This:

comboBox1.SelectedItem = comboBox1.Items[0]; 

OR

comboBox1.SelectedIndex = 0; //it is the index value

Upvotes: 0

Revan
Revan

Reputation: 1144

string Sql = "select status from lk_tb_project_status";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand com = new OleDbCommand(Sql, con);

con.Open();

comboBox1.Items.Insert(0,"Select Status");
OleDbDataReader DR = com.ExecuteReader();
while (DR.Read())
{
   comboBox1.Items.Add(DR[0]); 
}

Upvotes: 0

Richard Priddy
Richard Priddy

Reputation: 92

Use the FindString method to get the index of the first item in the ComboBox with the text "Sold". Then set the SelectedIndex to that:

comboBox1.SelectedIndex = comboBox1.FindString("Sold");

If it can't find the text "Sold" then the selected index will be -1 and the combo box will display a blank item by default.

Upvotes: 1

Related Questions