Click here to Skip to main content
15,888,212 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have this problem when I put the Binding Mode to TwoWay the DataGrid won't show. When I leave the Binding Mode as it is on default, the DataGrid will apear as strings, and I cannot find the problem. In XAML I have 3 more buttons: Load(that loads the table), Update and Cancel(that cancel all the changes and reloads the DataGrid directly from ObservableCollection.


Here is my XAML DataGrid line:
XML
<DataGrid x:Name="dataGrid" AutoGenerateColumns="True" Canvas.Left="10" Canvas.Top="10" AlternatingRowBackground="LightGreen" Height="245" Width="500" ItemsSource="{Binding Userss.UserCol, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" DataContext="{Binding RelativeSource={RelativeSource Self}}"/>



I have a Userss Class where i creat my ObservableCollection where i store the data from my SQLite database.
C#
<pre lang="C#">public class Userss : INotifyPropertyChanged
{
    public static SQLiteConnection m_dd = new SQLiteConnection("Data Source=MyDatabase.sqlite;Version=3;");

    private static ObservableCollection<userss> userCol = new ObservableCollection<userss>();

        public ObservableCollection<userss> UserCol
        {
            get { return userCol; }
            set
            {
                userCol = value;
                RaisePropertyChanged();
            }
        }
    public int Id { get; set; }
    private string _name;
    public string Name
    {
        get { return _name; }
        set
        {
            _name = value;
            RaisePropertyChanged();
        }
    }

    private Sex _sex;
    public Sex Sex
    {
        get { return _sex; }
        set
        {
            _sex = value;
            RaisePropertyChanged();
        }
    }

    private Stations _station;
    public Stations Station
    {
        get { return _station; }
        set
        {
            _station = value;
            RaisePropertyChanged();
        }
    }

    private Jobs _job;
    public Jobs Job
    {
        get { return _job; }
        set
        {
            _job = value;
            RaisePropertyChanged();
        }
    }

    private DateTime _date;
    public DateTime Date
    {
        get { return _date; }
        set
        {
            _date = value;
            RaisePropertyChanged();
        }
    }

    public static ObservableCollection<Userss> GetValues()
    {
        m_dd.Open();
        string sql = "select * from user";
        userCol.Clear();
        SQLiteCommand cmd = new SQLiteCommand(sql, m_dd);
        SQLiteDataReader reader = cmd.ExecuteReader();
        while (reader.Read())
        {
            string sex1 = reader["sex"].ToString();
            string station1 = reader["station"].ToString();
            string job1 = reader["job"].ToString();
            string data1 = reader["date"].ToString();
            userCol.Add(new Userss()
            {
                Id = Convert.ToInt32(reader["id"]),
                Name = reader["name"].ToString(),
                Sex = (Sex)Enum.Parse(typeof(Sex), sex1),
                Station = (Stations)Enum.Parse(typeof(Stations), station1),
                Job = (Jobs)Enum.Parse(typeof(Jobs), job1),
                Date = Convert.ToDateTime(data1)
            });
        }
        m_dd.Close();
        return userCol;

    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void RaisePropertyChanged([CallerMemberName] string caller = "")
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(caller));
        }
    }
}

public enum Sex
{
    Male,
    Female
}
public enum Jobs
{
    Programmer,
    Designer,
    Manager,
    CTO,
    CEO,
}
public enum Stations
{
    Desktop,
    Laptop,
    Tablet
}

And here is my implementation for my MainWindow:

C#
public partial class MainWindow : Window
    {
        public SQLiteConnection m_db = new SQLiteConnection("Data Source=MyDatabase.sqlite;Version=3;");
        SQLiteDataAdapter adap;
        DataSet ds;
        DataTable dt;
        SQLiteCommandBuilder cmdbl;
        string Query;
        public MainWindow()
        {
            InitializeComponent();
        }
        private void LoadButton_Click(object sender, RoutedEventArgs e)
        {
            dataGrid.ItemsSource = Userss.GetValues();
        }

        private void Update_Click(object sender, RoutedEventArgs e)
        {
            if (MessageBox.Show("Are you sure you want to make those changes?", "Please confirm", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
            {
                try
                {
                    m_db.Open();
                    cmdbl = new SQLiteCommandBuilder(adap);
                    Query = "Select * from user";
                    adap = new SQLiteDataAdapter(Query, m_db);
                    ds = new DataSet();
                    adap.Fill(ds, "Users");
                    dt = ds.Tables[0];
                    ds.Tables[0].AcceptChanges();
                    adap.Update(ds, "Users");
                    dt.AcceptChanges();
                    adap.Update(dt);
                    dataGrid.Items.Refresh();
                    m_db.Close();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                
            }
            else
                this.dataGrid.CancelEdit();
        }

        private void CancelClick(object sender, RoutedEventArgs e)
        {
            if (MessageBox.Show("Are you sure you want to cancel those changes?", "Please confirm", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
            {
                dataGrid.ItemsSource = Userss.GetValues();
            }
            else
                this.dataGrid.CancelEdit();
        }
    }
}

Btw I work in WPF.

Hope someone can help me. Thanks.



What I have tried:

I've tryed to debug and see what is happening with the dataset and data table and I saw that they don't change at all.
Posted
Updated 21-Nov-16 1:31am

1 solution

0) You need a public property to bind to.

public Userss Users { get; set; }

And you can set the DataContext in the constructor:

this.DataContext=this;

1) Why are you setting the ItemsSource in both the XAML and the code-behind?

2) Compartmentalize your code. Put the database query objects and code into a method. In fact, I would create a static class with my database stuff in it, and that way, it's not cluttering up your UI code.
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900