[C# 윈폼] Textbox 입력된 문자열로 ComboBox 데이터 Filter 기능 구현하기

안녕하세요.

 

오늘은 C# 윈폼에서 Textbox에 문자를 입력하면 해당 문자에 알맞게 Filter 가 되어 ComboBox 데이터가 나오게끔 하는 방법에 대해서 알려 드리려고 합니다.

 

바로 예제 코드를 통해서 보여 드리도록 하겠습니다.

 

먼저, 아래와 같이 빈 윈폼 프로젝트를 생성해 주시고, TextBox 컨트롤과 ComboBox 컨트롤을 배치해 주시기 바랍니다.

 

 

빈 윈폼 프로젝트 생성 및 컨트롤 배치

위와 같이 Textbox 컨트롤과 ComboBox 컨트롤을 배치해 주시기 바랍니다.

 

각각 컨트롤의 이름은 uiTxt_Filter, uiCb_Materials 이렇게 이름을 설정하겠습니다.

 

이제 그럼 비하인드 소스코드를 작성해서 저 위에 넣어둔 Items에서 Textbox 컨트롤에 입력된 문자열로 필터 되어서 보여 게끔 예제 코드를 작성해 보도록 하겠습니다.

 

예제 코드
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
 
namespace FilterTest
{
    public partial class Form1 : Form
    {
        List<string> comboList = new List<string>();
 
        public Form1()
        {
            InitializeComponent();
 
            this.uiTxt_Filter.TextChanged += uiTxt_Filter_Event;
 
            AddItems();
 
            //콤보박스 데이터 List에 저장
            ComboListAdd();
        }
 
        /// <summary>
        /// 콤보박스 데이터 List에 저장
        /// </summary>
        private void ComboListAdd()
        {
            for (int idx = 0; idx < uiCb_Materials.Items.Count; idx++)
            {
                comboList.Add(uiCb_Materials.Items[idx].ToString());
            }
        }
 
        /// <summary>
        /// 콤보박스 Item 저장
        /// </summary>
        private void AddItems()
        {
            uiCb_Materials.Items.Add("두리안");
            uiCb_Materials.Items.Add("바나나");
            uiCb_Materials.Items.Add("키위");
            uiCb_Materials.Items.Add("사과");
            uiCb_Materials.Items.Add("토마토");
            uiCb_Materials.Items.Add("망고");
            uiCb_Materials.Items.Add("애플망고");
            uiCb_Materials.Items.Add("포도");
            uiCb_Materials.Items.Add("거봉");
            uiCb_Materials.Items.Add("호두");
        }
 
 
        /// <summary>
        /// TextBox 텍스트 변화 이벤트 핸들러
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void uiTxt_Filter_Event(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;
 
            uiCb_Materials.Items.Clear();
            ComboListAdd();
 
            string filterString = uiTxt_Filter.Text.ToString();
 
            var result = comboList.Where(x => x.Contains(filterString)).ToArray();
 
            uiCb_Materials.Items.AddRange(result);
 
            this.Cursor = Cursors.Default;
        }
    }
}
 
cs

 

실행 결과

위와 같이 Filter 기능이 제대로 된 것을 확인하실 수 있습니다.

 

감사합니다.^^

728x90

이 글을 공유하기

댓글

Designed by JB FACTORY