b

Saturday, 15 December 2012

datagrid in wpf example

Datagrid in wpf example

  • Create WPF Project  using VS 2012 C#
  • Drag and Drop Datagrid and Label into Grid Layout

 <Grid>
        <DataGrid x:Name="datagrid1" HorizontalAlignment="Left" VerticalAlignment="Top" Height="217" Margin="0,80,0,0" Width="758"/>
        <TextBlock HorizontalAlignment="Left" TextWrapping="Wrap" Text="DataGrid Demo in WPF" VerticalAlignment="Top" Height="59" Width="723" FontSize="22"/>
    </Grid>

  • Add a Class called Customers 
 public class Customers
    {
        public int custID { get; set; }
        public String Name { get; set; }
        public DateTime DOB { get; set; }
        public DateTime MemberSince { get; set; }
        public String emailID { get; set; }
    }


  • Fill Customer List with sample data.
  void FillData()
        {
            custList.Add(new Customers { custID = 1, DOB = new DateTime(1973, 12, 12,10,20,10), emailID = "p_pathi2020@yahoo.com", MemberSince = new DateTime(2000, 12, 12), Name = "Peter hans" });
            custList.Add(new Customers { custID = 2, DOB = new DateTime(1973, 12, 12), emailID = "sam@yahoo.com", MemberSince = new DateTime(2000, 12, 12), Name = "sam benegal" });
            custList.Add(new Customers { custID = 3, DOB = new DateTime(1983, 12, 12), emailID = "paul@yahoo.com", MemberSince = new DateTime(2000, 12, 12), Name = "Paul hons" });
            custList.Add(new Customers { custID = 4, DOB = new DateTime(1993, 12, 12), emailID = "pari@yahoo.com", MemberSince = new DateTime(2000, 12, 12), Name = "whiteman pari" });
            custList.Add(new Customers { custID = 5, DOB = new DateTime(1988, 12, 12), emailID = "pron@yahoo.com", MemberSince = new DateTime(2000, 12, 12), Name = "Porn star" });
        }

  • Binding DataGrid to CustomerList in WPF

List<Customers> custList = new List<Customers>();

        public datagrid2()
        {
            InitializeComponent();
            this.Loaded += datagrid2_Loaded;
        }

        void datagrid2_Loaded(object sender, RoutedEventArgs e)
        {
            FillData();

            datagrid1.ItemsSource = custList;
        }


OUTPUT

No comments:

Post a Comment