Home > Software engineering >  C# Combo box default value
C# Combo box default value

Time:05-25

I am trying to make SQL statement based on item selected throw combo box. I want to have default item selected as ID, but now it returns NULL. What am I doing wrong?

private void Win_Shown(object sender, EventArgs e)
{
   myBox.SelectedValue = "ID";
   myBox.SelectedText = "ID";
   myBox.SelectedItem = "ID";

   myBox.Items.Add("ID");
   myBox.Items.Add("Name");
   myBox.Items.Add("Surname");
   myBox.Items.Add("Mobile"); 
}

Then in for SQL statement

MySQL.DisplayAndSearch("SELECT * FROM Data WHERE "   this.myBox.SelectedItem.ToString()   " LIKE '%"   txt_Search.Text   "%'", dataGridView1);

Thank for any help :)

CodePudding user response:

You are selecting the item before inserting:

private void Win_Shown(object sender, EventArgs e)
{
   // first, add the items   
   myBox.Items.Add("ID");
   myBox.Items.Add("Name");
   myBox.Items.Add("Surname");
   myBox.Items.Add("Mobile"); 

   // now select it
   myBox.SelectedItem = "ID";
}

CodePudding user response:

Have you tried?

        private void Win_Shown(object sender, EventArgs e)
    {
    
       myBox.Items.Add("ID");
       myBox.Items.Add("Name");
       myBox.Items.Add("Surname");
       myBox.Items.Add("Mobile"); 

// now select it
            myBox.SelectedIndex = myBox.FindString("Mobile");//id..etc
    }
  • Related