728x90

combobox 컨트롤은 여러개의 아이템 중에서 하나를 고를때 선택한다.



도구상자에서 comboBox 를 추가하면 default 는 DropDown 이 선택된다. 직접 변경하려면 DropDownStyle이라는 속성에서 지정한다.


private void AddComboBox() // 콤보박스에 추가
{  
   comboBox1.Items.Add(textBox1.Text); // 항목을 추가
 
   if (comboBox1.Items.Count > 0) // 항목이 있으면, 방금 입력한 항목을 선택
      comboBox1.SelectedIndex = comboBox1.Items.Count - 1;
}

private void GetComboBox()  // 콤보박스 선택을 TextBox1 에 표시
{
   textBox1.Text = comboBox1.SelectedItem.ToString();
}


private void Form1_Load(object sender, EventArgs e)
 {
       comboBox1.Items.Add("Item 1");
       comboBox1.Items.Clear();
        comboBox1.Items.AddRange(new string[] { "나미", "현숙", "효린" });
 }


private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    if (comboBox1.SelectedIndex >= 0)  // index 는 0 부터 시작됨
    {
          cate1.Text = comboBox1.SelectedItem.ToString();  // SelectedItem 은 선택된 값
          textBox1.Text = comboBox1.SelectedIndex.ToString();  // Index 는 0, 1, 2
          MessageBox.Show(comboBox1.SelectedItem.ToString());
     }
}




comboBox1을 선택하면 comboBox2 의 값이 변하게 하는 방법을 알아보자.

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{           
     if (comboBox1.SelectedIndex >= 0)  // index 는 0 부터 시작됨
     {
          cate1.Text = comboBox1.SelectedItem.ToString();
          textBox1.Text = comboBox1.SelectedIndex.ToString();
      }
      if (comboBox1.SelectedIndex == 0)
      {
           comboBox2.Items.Clear();
           comboBox2.Items.Add("A1");
           comboBox2.Items.Add("A2");
           comboBox2.Items.Add("A3");
      }
      else if (comboBox1.SelectedIndex == 1)
      {
           comboBox2.Items.Clear();
           comboBox2.Items.Add("B1");
           comboBox2.Items.Add("B2");
           comboBox2.Items.Add("B3");
      }
      else if (comboBox1.SelectedIndex == 2)
      {
           comboBox2.Items.Clear();
           comboBox2.Items.Add("C1");
           comboBox2.Items.Add("C2");
      }
}





블로그 이미지

Link2Me

,