본문 바로가기
C++ 200제/코딩 IT 정보

C# ListBox 리스트박스 사용 예제 (DB 바운딩, List 응용 등)

by vicddory 2017. 3. 9.

C# ListBox 리스트박스 사용법과 예제 (DB 바운딩, List 응용 등)


C# 리스트박스를 사용하여 원하는 항목 중 일부를 사용자에게 보여줄 수 있습니다.


ListBox 선택된 항목 띄우기[System.Windows.Forms 클래스] ListBox 선택된 항목 띄우기


보여주거나 선택하는 기능 외에도 목록을 편집할 수 있는 기능도 있습니다. Add 함수로 ListBox의 맨 끝에 목록을 추가할 수 있습니다.


1
listBox1.Items.Add ("Sunday");
cs


C# 리스트박스에서 선택한 하나의 항목을 변수처럼 사용하려면 아래와 같이 코드를 작성할 수 있습니다.


1
2
string var;
var = listBox1.Text;
cs


SelectionMode 속성은 선택할 수 있는 아이템이 한 개인지 여러 개인지 나타냅니다. 속성값을 Multiple Select로 변경하면 많은 아이템을 선택할 수 있죠.


1
listBox1.SelectionMode = SelectionMode.MultiSimple;
cs


아래 예제는 윈도우 폼을 로드할 때 리트스 박스에 요일을 추가한 뒤, 다중 선택을 할 수 있도록 설정합니다.


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
using System;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            listBox1.Items.Add("Sunday");
            listBox1.Items.Add("Monday");
            listBox1.Items.Add("Tuesday");
            listBox1.Items.Add("Wednesday");
            listBox1.Items.Add("Thursday");
            listBox1.Items.Add("Friday");
            listBox1.Items.Add("Saturday");
            listBox1.SelectionMode = SelectionMode.MultiSimple;
        }
        private void button1_Click(object sender, EventArgs e)
        {
            foreach (Object obj in listBox1.SelectedItems )
            {
                MessageBox.Show(obj.ToString ());
            }
        }
    }
}
cs

C# 리스트박스에 리스트를 바인딩하는 방법

먼저 List 객체를 생성하고 그곳에 데이터를 추가합니다.


1
2
3
4
5
List<string> nList = new List<string>();
nList.Add("January");
nList.Add("February");
nList.Add("March");
nList.Add("April");
cs


ListBox 데이터 바인딩[System.Windows.Forms 클래스] ListBox 데이터 바인딩


이어서, DataSource 속성을 이용해 List를 ListBox에 바인딩합니다.


1
listBox1.DataSource = nList;
cs


전체 소스


1
2
3
4
5
6
7
8
9
private void button1_Click(object sender, EventArgs e)
{
    List<string> nList = new List<string>();
    nList.Add("January");
    nList.Add("February");
    nList.Add("March");
    nList.Add("April");
    listBox1.DataSource = nList;
}
cs

C# 리스트박스에 데이터베이스 바인딩하는 방법

먼저 connection와 fetch를 할 수 있도록 쿼리문을 작성합니다.


1
2
3
4
5
6
connetionString = "Data Source=ServerName;
                   Initial Catalog=databasename;
                   User ID=userid;
                   Password=yourpassword";
 
sql = "select au_id,au_lname from authors";
cs


이어서, 리스트박스의 datasource를 DB의 것으로 설정합니다.


1
2
3
listBox1.DataSource = ds.Tables[0];
listBox1.ValueMember = "au_id";
listBox1.DisplayMember = "au_lname";
cs


ListBox DB 데이터 바인딩[System.Windows.Forms 클래스] ListBox DB 데이터 바인딩


전체 소스


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
using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            string connetionString = null;
            SqlConnection connection;
            SqlCommand command;
            SqlDataAdapter adapter = new SqlDataAdapter();
            DataSet ds = new DataSet();
            int i = 0;
            string sql = null;
            //connetionString = "Data Source=ServerName;Initial Catalog=databasename;User ID=userid;Password=yourpassword";
            //sql = "select au_id,au_lname from authors";
            connection = new SqlConnection(connetionString);
            try
            {
                connection.Open();
                command = new SqlCommand(sql, connection);
                adapter.SelectCommand = command;
                adapter.Fill(ds);
                adapter.Dispose();
                command.Dispose();
                connection.Close();
                listBox1.DataSource = ds.Tables[0];
                listBox1.ValueMember = "au_id";
                listBox1.DisplayMember = "au_lname";
            }
            catch (Exception ex)
            {
                MessageBox.Show("Cannot open connection ! ");
            }
        }
    }
}
cs

ListBox의 DataSource를 갱신하는 방법

C# 리스트박스 - 이미 반영된 데이터 소스를 삭제하는 방법

리스트박스가 DataSource를 바인딩했다면, 이를 null로 바꿔야 합니다.


1
listBox1.DataSource = null;
cs


SelectedIndexChanged 이벤트 사용 방법

이 이벤트는 사용자가 선택한 아이템이 변경되면 발생합니다. 속성 창에서 SelectedIndexChanged 항목을 찾아보세요.


SelectedIndexChanged 창[System.Windows.Forms 클래스] SelectedIndexChanged 창


해당 항목을 더블 클릭하면 자동으로 이벤트 함수가 생성됩니다.


1
2
3
4
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
 
}
cs


다음 예제에선 SelectedIndexChanged 이벤트를 발생시키는 방법을 살펴봅니다.


SelectedIndexChanged 소스 코드[System.Windows.Forms 클래스] SelectedIndexChanged 소스 코드


먼저 C# 리스트박스 두 개를 폼에 생성합니다. 그리고 아래처럼 첫 번째 리스트박스의 DataSource에 List를 바인딩합니다.


1
2
3
List<string> nList = new List<string>();
nList.Add("First Quarter");
nList.Add("Second Quarter");
cs


프로그램을 처음 실행하면 첫 번째 리스트박스에 데이터가 채워지고, 항목에 맞춰 두 번째 리스트박스에도 데이터가 채워집니다.


아래 코드에 구현 방법이 나와 있습니다.


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
using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
using System.Collections.Generic;
 
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
 
        List  < string > fQ = new List  < string > ();
        List  < string > sQ = new List  < string > ();
      
        private void Form1_Load(object sender, EventArgs e)
        {
            fQ.Add("January");
            fQ.Add("February");
            fQ.Add("March");
 
            sQ.Add("April");
            sQ.Add("May");
            sQ.Add("June");
 
            List < string > nList = new List  < string > ();
 
            nList.Add("First Quarter");
            nList.Add("Second Quarter");
 
            listBox1.DataSource = nList;
        }
 
        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listBox1.SelectedIndex == 0)
            {
                listBox2.DataSource = null;
                listBox2.DataSource = fQ;
            }
            else if (listBox1.SelectedIndex == 1)
            {
                listBox2.DataSource = null;
                listBox2.DataSource = sQ;
            }
        }
    }
}
cs


출처 - C# ListBox Control [클릭]


C# ListBox 리스트박스 사용 예제 (DB 바운딩, List 응용 등)


댓글