본문 바로가기
공부,일/C#

Window Forms 리스트 박스 ,콤보 박스

by fromnothing1 2021. 6. 11.

데이터를 묶어서 관리할 수 있다.

 

콤보박스 입력 방법

List<string> aList1 = new List<string>();
        
        public Form1()
        {

            InitializeComponent();
            aList1.Add("감자");
            aList1.Add("고구마");
            aList1.Add("사과");

            //comboBox 는 List 클래스를 지원함 
            comboBox1.DataSource = aList1;
            
        }

콤보 박스는 List 클래스를 지원한다.

실행 모습

  private void comboBox1_SelectionChangeCommitted(object sender, EventArgs e)
        {
            // MessageBox.Show((((ComboBox)sender).SelectedIndex).ToString()); //선택된 객체의 인덱스 
            MessageBox.Show((((ComboBox)sender).SelectedItem).ToString()); // 선택된 객체의 스트링
        
        }
        
  
        private void listBox1_MouseDown(object sender, MouseEventArgs e)
        {
            MessageBox.Show((((ListBox)sender).SelectedItem).ToString()); // 선택된 객체의 스트링
        }

 

위와 같은 코드로 콤보 박스와 리스트 박스에서 선택된 객체에 대한 정보를 얻을 수 있다 .

 

 

콤보 박스 클래스 사용 예제 

 public partial class Form1 : Form
    {

        List<Cafe> aList1 = new List<Cafe>();
        
        public Form1()
        {
            InitializeComponent();
            aList1 = new List<Cafe>
            {
                new Cafe(){ Name = "라떼" , Price = 1500},
                new Cafe(){ Name = "아아" , Price = 2500},
                new Cafe(){ Name = "돌체라떼" , Price = 3500},
                new Cafe(){ Name = "녹차라떼" , Price = 4500},
                new Cafe(){ Name = "콜드블루" , Price = 5500},
                new Cafe(){ Name = "버블티" , Price = 6500}
            };

            comboBox1.DataSource = aList1;
            comboBox1.DisplayMember = "Name"; // 화면에 출력할 멤버 정하기 
            comboBox1.ValueMember = "Price"; // 데이터가 가지는 value 설정 

        }

        private void comboBox1_SelectionChangeCommitted(object sender, EventArgs e)
        {
            ComboBox aComboBox;
            Cafe aCafe;

            aComboBox = (ComboBox)sender;
            //SelectedItem 은 항상 object 객체를 return 한다.
            aCafe = (Cafe)(aComboBox.SelectedItem);

            MessageBox.Show("이름 :" + aCafe.Name + "\n가격 :"+ aCafe.Price.ToString() );

        }
    }
    

 

실행 모습

결국 형변환이 중요하다. 

 

물론 위에서 우리가 

comboBox1.DisplayMember = "Name";
comboBox1.ValueMember = "Price";  

 

를 정해 줬기 때문에 

ComboBox 의

aComboBox.SelectedText

aComboBox.SelectedValue

속성으로 접근 가능하다.

'공부,일 > C#' 카테고리의 다른 글

c# 에서 다차원 배열  (0) 2021.06.13
WinForms DataGridView  (0) 2021.06.11
예외처리  (0) 2021.06.10
enum 열거형 다중지정 방식  (0) 2021.06.10
210608  (0) 2021.06.08

댓글