ADO.NET에서 사용하는 DataSet을 WPF의 DataGrid 컨트롤에 바인딩하려면,
DataGrid의 ItemsSource 속성에 DataSet.Table[0].Default 속성을 지정하면된다.
샘플 코드는 아래와 같다.
<Window x:Class="WpfAddressBook.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<DataGrid AutoGenerateColumns="True" HorizontalAlignment="Left" Margin="90,169,0,44" Name="ctlAddressList" Width="278" />
<TextBox Height="23" HorizontalAlignment="Left" Margin="116,42,0,0" Name="txtAddress" Text="TextBlock" VerticalAlignment="Top" />
<Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="253,42,0,0" Name="btnAdd" VerticalAlignment="Top" Width="75" Click="btnAdd_Click" />
</Grid>
</Window>
using System.Data;
using System.Data.SqlClient;
using System.Windows;
namespace WpfAddressBook
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler(MainWindow_Loaded);
}
void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "server=.;database=AB;uid=AB;pwd=AB;";
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "Select * From AddressBook";
cmd.CommandType = System.Data.CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds, "AddressBook");
this.ctlAddressList.ItemsSource = ds.Tables[0].DefaultView;
}
private void btnAdd_Click(object sender, RoutedEventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "server=.;database=AB;uid=AB;pwd=AB;";
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "Insert Into AddressBook Values('" + txtAddress.Text + "')";
cmd.CommandType = System.Data.CommandType.Text;
cmd.ExecuteNonQuery();
MessageBox.Show("저장 완료");
MainWindow_Loaded(null, null);
}
}
}