Wednesday, 11 August 2010

WPF DataTable example

<Window x:Class="WpfTable.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    DataContext="{Binding RelativeSource={RelativeSource Self}}"
    Title="WPF Tables" Height="300" Width="524">
    <Grid>
        <StackPanel>
            <Grid Background="AliceBlue">
                <Label Content="Basic Table"/>
                <Button Content="Add Row" Margin="5,5,5,5" Click="Button_Click" HorizontalAlignment="Right"/>
            </Grid>            
            <ListView x:Name="listView1" Height="100" ItemsSource="{Binding Path=DataTable}" Background="WhiteSmoke" SelectionChanged="listView1_SelectionChanged" ToolTip="Click to Remove Row">
                <ListView.View>
                    <GridView x:Name="gridView1">
                        <GridView.Columns>
                            <GridViewColumn Header="Number" DisplayMemberBinding="{Binding Path=Number}" Width="100"/>
                            <GridViewColumn Header="Text" DisplayMemberBinding="{Binding Path=Text}" Width="100"/>
                        </GridView.Columns>
                    </GridView>
                </ListView.View>
            </ListView>
        </StackPanel>
    </Grid>
</Window>

 

public partial class Window1 : Window
    {
        private DataTable dataTable = new DataTable();
        public Window1()
        {
            Init();
            InitializeComponent();            
        }
        private void Init()
        {
            dataTable = new DataTable();
            dataTable.Columns.Add("Number", typeof(int));
            dataTable.Columns.Add("Text", typeof(string));
            dataTable.Columns.Add("NotVisible", typeof(string));
            DataRow row = dataTable.NewRow();
            row["Number"] = 1;
            row["Text"] = "Row 1";
            row["NotVisible"] = "You don't see me";
            dataTable.Rows.Add(row);
        }
        public DataTable DataTable
        {
            get
            {                
                return dataTable;
            }
        }
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            DataRow row = dataTable.NewRow();
            int nextRow = dataTable.Rows.Count + 1;
            row["Number"] = nextRow;
            row["Text"] = string.Format("Row {0}", nextRow);
            row["NotVisible"] = "You don't see me";
            dataTable.Rows.Add(row);
        }
        private void listView1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if(e.AddedItems.Count>0)
            {
                DataRowView rowView = (DataRowView)e.AddedItems[0];
                DataRow row = rowView.Row;                 
                dataTable.Rows.Remove(row);
            }
        }       
    }

No comments:

Post a Comment