Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: WPF MVVM DataGrid Binding
am completely new to MVVM. I was trying to bind the data from sqlserver to the Datagrid in WPF and perform Edit, update and delete operations on it. now, am unable to bind the data from sqlserver to datagrid atleast using observable collection in MVVM.... someone please help me out to resolve it and also kindly let me know how to implement the edit,update and delete operations for the same datagrid....am totally getting confused implementing the MVVM architecture..
 
with the following code i could bind the data to "Empdata"(observablecollection) but the datagrid is not being displayed at all.
 
the following is my xaml code :
 
<datagrid itemssource="{Binding Path=Empdata}" x:name="dtgrdemp" xmlns:x="#unknown">
             AutoGenerateColumns="False"
             SelectionMode="Single"
             SelectionUnit="FullRow"
             GridLinesVisibility="Horizontal"
             CanUserDeleteRows="True"
             CanUserAddRows="False">
 
the following is my code for "view" where i took a class as person
 
 public class Person : INotifyPropertyChanged, IDataErrorInfo
{
    private string names;
 
    public string Names
    {
        get { return names; }
        set
        {
            names = value;
            OnPropertyChanged("Names");
        }
    }
 
    private int age;
 
    public int Age
    {
        get { return age; }
        set
        {
            age = value;
            OnPropertyChanged("Age");
        }
    }
 
    private string description;
 
    public string Description
    {
        get { return description; }
        set
        {
            description = value;
            OnPropertyChanged("Description");
        }
    }
 

 
    public event PropertyChangedEventHandler PropertyChanged;
 
    protected void OnPropertyChanged(string propertyname)
    {
        var handler = PropertyChanged;
        if (handler != null)
            handler(this, new PropertyChangedEventArgs(propertyname));
    }
 public string Error
    {
        get { return null; }
    }
 
    public string this[string columnName]
    {
        get
        {
            string error = null;
            switch (columnName)
            {
                case "Names":
                    if (string.IsNullOrEmpty(names))
                    {
                        error = "First Name required";
                    }
                    break;
 
                case "Age":
                    if ((age < 18) || (age > 85))
                    {
                        error = "Age out of range.";
                    }
                    break;
                case "Description":
                    if (string.IsNullOrEmpty(description))
                    {
                        error = "Last Name required";
                    }
                    break;
            }
            return (error);
 

        }
    }
 
the following is my code for "ViewModel" class
 
public class MainViewModel :INotifyPropertyChanged
{
    string con = ConfigurationSettings.AppSettings["ConnectionStrings"];
    ObservableCollection<empinfo> Empdata= new ObservableCollection<empinfo>();
 

    private Person empperson;
 
    public Person Empperson
    {
        get { return empperson; }
        set { empperson = value; }
    }
 
    public MainViewModel()
    {
        initializeload();
    }
 
    private void initializeload()
    {
        DataTable dt = new DataTable();
        Empdata = new ObservableCollection<empinfo>();
        Empdata.Add(new EmpInfo(dt));
 
    }
 
    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged(string propertyname)
    {
        var handler = PropertyChanged;
        if (handler != null)
            handler(this, new PropertyChangedEventArgs(propertyname));
    }
}
the following is the code for EmpInfo.cs class
 
 public EmpInfo(DataTable dt)
    {
        SqlConnection sqlcon = new SqlConnection(con);
        sqlcon.Open();
        SqlDataAdapter da = new SqlDataAdapter("Select Ename,Eage,Edescription from EmployeeTable", sqlcon);
        da.Fill(dt);
        this.dt = dt;
    }
the following is the code in Appxaml.cs
 
 protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);
        var mainWindow = new MainWindow();
        var viewModel = new MainViewModel();
        mainWindow.DataContext = viewModel;
        mainWindow.Show();
    }</empinfo></empinfo></empinfo>
 
Thanks in advance.
Posted 13-Sep-11 3:04am
Edited 13-Sep-11 3:10am
v2
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

To start with, binding to datasets and datatables is not the best solution in WPF applications, you really should use ADO.Net and a DataReader to convert your database info into CLR objects, in this case an ObservableCollection<employees>. You can then bind you datagrid to the collection, rather than a datatable. Secondly, with regard to editing an employees record in the grid, you should have specific buttons which the user can use to edit, save and cancel edit. These buttons would be bound to ICommand properties in your viewmodel, which would then call the data access layer to update or insert records using ADO.Net.
 
Hope this helps
  Permalink  
Comments
Simon Bang Terkildsen at 13-Sep-11 9:27am
   
+5
Wayne Gaylard at 13-Sep-11 9:36am
   
Thanks!
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

Make MainViewModel.Empdata public, and do not initialize it twice it's not an error just redundant.
 
My article might also be able to help you now and in the future
Debugging WPF data bindings[^]
It might be tricky to understnd if you're really that new to data binding in WPF, but you're always welcome to leave any questions you might have on the discussion of that article.
  Permalink  

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
0 OriginalGriff 279
1 Maciej Los 168
2 George Jonsson 154
3 Sarvesh Kumar Gupta 130
4 Dave Kreskowiak 130


Advertise | Privacy | Mobile
Web03 | 2.8.140709.1 | Last Updated 13 Sep 2011
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid