Tuesday, April 12, 2016

WPF - Binding the datas of DataTable on ComboBox.

It is the way binding the datas of DataTable on ComboBox.

1. Add ComboBox on the Window.
























 2. Type ComboBox name.








3. Add Initialized Event on Window.

















 4. Add SelectionChanged event of ComboBox.

















5. Type below codes on Window's code file.
 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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data;

namespace ComboBoxBinding
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Window_Initialized(object sender, EventArgs e)
        {
            // Create DataTable instance.
            DataTable dataTable = new DataTable();

            // Add the colums in DataTable.
            dataTable.Columns.Add("VALUE", typeof(string));
            dataTable.Columns.Add("NAME", typeof(string));

            // Add the datas in DataTable.
            dataTable.Rows.Add(new string[] { "KR", "Korea" });
            dataTable.Rows.Add(new string[] { "US", "America" });
            dataTable.Rows.Add(new string[] { "CH", "China" });
            dataTable.Rows.Add(new string[] { "JP", "Japan" });

            // Binding DataView of DataTable on ComboBox.
            comboBox.ItemsSource = dataTable.DefaultView;
            // Set DisplayMemberPath attribute.
            comboBox.DisplayMemberPath = "NAME";
            // Set SelectedValuePath attribute.
            comboBox.SelectedValuePath = "VALUE";
        }

        private void comboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            // Check the slected data.
            foreach (DataRowView row in e.AddedItems)
            {
                MessageBox.Show("Value : " + row["VALUE"] + "\n" + "Name : " + row["NAME"]);
            }
        }
    }
}


6. Below images is result.











Refer below vedio.

No comments:

Post a Comment