b

Saturday, 15 December 2012

How to Bind a Datatable in dataSet to a WPF dataGrid in C# and XAML



How to Bind a Datatable in dataSet to a WPF dataGrid  in C# and XAML       


  • Create  a WPF Project using C#
  • Add 2 classes 
  •      Customers
  •       GetDataSet

            Customers class
 public class Customer
    {
        public int ID { get; set; }
        public String FirstName { get; set; }
        public String LastName { get; set; }
    }


GetDataset class

 public class GetDataset
    {
       DataSet dataset = new DataSet();
       void builddataset()
        {
            dataset.Clear();
            if (dataset.Tables.Count > 0)
            {
                dataset.Tables[01].Constraints.Clear();
                dataset.Tables[0].Constraints.Clear();

            }
            dataset.Tables.Clear();
            DataTable table = new DataTable("SalesData");
            DataColumn id = new DataColumn("ID", typeof(System.Int64));
            id.AutoIncrement = true;
            id.AutoIncrementSeed = 100;
            DataColumn salesman = new DataColumn("Sales Name", typeof(System.String));
            DataColumn SalesManID = new DataColumn("Emp ID", typeof(System.Int32));
            DataColumn yr2003 = new DataColumn("2003", typeof(System.Int32));
            DataColumn yr2004 = new DataColumn("2004", typeof(System.Int32));
            DataColumn yr2005 = new DataColumn("2005", typeof(System.Int32));
            DataColumn yr2006 = new DataColumn("2006", typeof(System.Int32));
            DataColumn yr2007 = new DataColumn("2007", typeof(System.Int32));

            table.Columns.Add(id);
            table.Columns.Add(salesman);
            table.Columns.Add(yr2003); table.Columns.Add(yr2004); table.Columns.Add(yr2005);
            table.Columns.Add(yr2006); table.Columns.Add(yr2007); table.Columns.Add(SalesManID);

            DataRow row = table.NewRow();
            row[1] = "Shayam"; row[2] = 5000; row[3] = 6000; row[4] = 6000; row[5] = 8000; row[6] = 10000; row[7] = 11;
            table.Rows.Add(row);
            row = table.NewRow();
            row[1] = "Benegal"; row[2] = 8000; row[3] = 9000; row[4] = 10000; row[5] = 12000; row[6] = 14000; row[7] = 12;
            table.Rows.Add(row);
            row = table.NewRow();
            row[1] = "Rowdy rathore"; row[2] = 8000; row[3] = 9000; row[4] = 10000; row[5] = 12000; row[6] = 14000; row[7] = 13;
            table.Rows.Add(row);

            row = table.NewRow();
            row[1] = "talaash"; row[2] = 8000; row[3] = 9000; row[4] = 10000; row[5] = 12000; row[6] = 14000; row[7] = 14;
            table.Rows.Add(row);


            DataTable personalDetailsTbl = new DataTable("EmpDetails");
            DataColumn ID = new DataColumn("ID", typeof(System.Int32));
            ID.AutoIncrement = true;
            ID.AutoIncrementSeed = 11;
            ID.ReadOnly = true;
            DataColumn FirstName = new DataColumn("FirstName", typeof(System.String));
            DataColumn LastName = new DataColumn("LastName", typeof(System.String));
            DataColumn HireDate = new DataColumn("HireDate", typeof(System.DateTime));
            DataColumn Dept = new DataColumn("Department", typeof(System.Int32));
            DataColumn CTC = new DataColumn("Cost to Company", typeof(System.Single));
            personalDetailsTbl.Columns.Add(ID); personalDetailsTbl.Columns.Add(FirstName); personalDetailsTbl.Columns.Add(LastName);
            personalDetailsTbl.Columns.Add(HireDate); personalDetailsTbl.Columns.Add(Dept); personalDetailsTbl.Columns.Add(CTC);
            personalDetailsTbl.Constraints.Add("PrimaryKey_EmpID", ID, true);
            DataRow PersonalRow = personalDetailsTbl.NewRow();
            PersonalRow[1] = "Shyam"; PersonalRow[2] = "Prasad"; PersonalRow[3] = new System.DateTime(2000, 10, 12);
            PersonalRow[4] = 10; PersonalRow[5] = 10000.33f;
            personalDetailsTbl.Rows.Add(PersonalRow);
            PersonalRow = personalDetailsTbl.NewRow();
            PersonalRow[1] = "Benegal"; PersonalRow[2] = "Prasad"; PersonalRow[3] = new System.DateTime(2012, 10, 12);
            PersonalRow[4] = 10; PersonalRow[5] = 11100.33f;
            personalDetailsTbl.Rows.Add(PersonalRow);
            PersonalRow = personalDetailsTbl.NewRow();
            PersonalRow[1] = "Rowdy Rathore"; PersonalRow[2] = "Kirshna"; PersonalRow[3] = new System.DateTime(1990, 10, 12);
            PersonalRow[4] = 10; PersonalRow[5] = 5555.55f;
            personalDetailsTbl.Rows.Add(PersonalRow);
            PersonalRow = personalDetailsTbl.NewRow();
            PersonalRow[1] = "talaash"; PersonalRow[2] = "Prasad"; PersonalRow[3] = new System.DateTime(1983, 10, 12);
            PersonalRow[4] = 10; PersonalRow[5] = 77677.77f;
            personalDetailsTbl.Rows.Add(PersonalRow);

            dataset.Tables.Add(personalDetailsTbl);
            dataset.Tables.Add(table);

            DataColumn parentCol = dataset.Tables["EmpDetails"].Columns["ID"];
            DataColumn childCol = dataset.Tables["SalesData"].Columns["Emp ID"];
            ForeignKeyConstraint fconstraint = new ForeignKeyConstraint(parentCol, childCol);
            //DataRelation relation = new DataRelation("foreign_key_id", parentCol, childCol);
            //relation.ParentTable.TableName = "EmpDetails";
            //relation.ChildTable.TableName = "SalesData";
            //dataset.Relations.Add(relation);
            fconstraint.UpdateRule = Rule.None;
            fconstraint.DeleteRule = Rule.None;
            fconstraint.AcceptRejectRule = AcceptRejectRule.None;
            dataset.Tables[1].Constraints.Add(fconstraint);
            dataset.EnforceConstraints = true;

        }
       public List<Customer> GetTable()
       {
           builddataset();
           var query = from t in dataset.Tables[0].AsEnumerable()
                       select new Customer { ID = t.Field<System.Int32>("ID"), FirstName = t.Field<System.String>("FirstName"), LastName = t.Field<String>("LastName") };

           return query.ToList();
       }
       public DataTable GetSingleTable()
       {
           builddataset();

           return dataset.Tables[0];
       }
    }


  • Add Button and DataGird  to Grid Layout in XAML
 <Button x:Name="populate" Click="populate_Click" Margin="342,194,10,32"  />
        <DataGrid HorizontalAlignment="Left" VerticalAlignment="Bottom" AutoGenerateColumns="False"
                     x:Name="datagrid1" Margin="10,0,0,10" Height="134" Width="269" Loaded="datagrid1_Loaded"
                   ItemsSource="{Binding}"
                  >
            <DataGrid.Resources>
                <local:GetDataset x:Key="mydatasetKey" x:Name="myDataSet"></local:GetDataset>
            </DataGrid.Resources>
            <DataGrid.Columns>
                <DataGridHyperlinkColumn   Header="EMP ID"  Binding="{Binding Path=ID}"/>
                <DataGridTextColumn  Header="FirstName" Binding="{Binding Path=FirstName}"/>
                <DataGridTextColumn Header="LastName" Binding="{Binding Path=LastName}"/>
            </DataGrid.Columns>
        </DataGrid>

  • Button Event Handler
        private void populate_Click(object sender, RoutedEventArgs e)
        {
            try
            {

               // this.Content = new datagrid2();

                GetDataset ds = new GetDataset();
                customers = ds.GetTable();
                //datagrid1.DataContext = ds.GetTable();
                datagrid1.ItemsSource = ds.GetSingleTable().DefaultView;
                
                
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

OUTPUT


No comments:

Post a Comment