如何从DataGrid中添加新行或从DataBase中删除一行

时间:2016-11-23 12:04:08

标签: c# wpf sqlite data-binding datagrid

所以我在WPF中有这个学校项目,我必须将DataGrid绑定到SQLite DataBase。在XAML我还有3个buttonsLoad(加载表格),UpdateCancel(取消所有更改并重新加载{{ 1}}直接来自DataGrid。 我在这里有ObservableCollection行:

XAML

我有一个<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}}"/> Userss我创建了Class,用于存储ObservableCollection SQLite中的数据。

database

这是我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 id,name,sex,station,job,date 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 }}

的实施方式
MainWindow

我遇到的问题是,当我按下public partial class MainWindow : Window { public SQLiteConnection m_db = new SQLiteConnection("Data Source=MyDatabase.sqlite;Version=3;"); ObservableCollection<Userss> usersCollection = Userss.GetValues(); public MainWindow() { InitializeComponent(); } private void LoadButton_Click(object sender, RoutedEventArgs e) { try { dataGrid.ItemsSource = Userss.GetValues(); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } } 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(); foreach (var user in usersCollection) { string sql = "UPDATE user SET Name = @name, Sex = @sex, Station = @station, Job = @job, Date = @date WHERE Id = @id"; SQLiteCommand command = new SQLiteCommand(sql, m_db); command.Parameters.Add(new SQLiteParameter("@name", user.Name)); command.Parameters.Add(new SQLiteParameter("@sex", user.Sex.ToString())); command.Parameters.Add(new SQLiteParameter("@station", user.Station.ToString())); command.Parameters.Add(new SQLiteParameter("@job", user.Job.ToString())); command.Parameters.Add(new SQLiteParameter("@date", user.Date.ToString())); command.Parameters.Add(new SQLiteParameter("@id", user.Id.ToString())); command.ExecuteNonQuery(); } m_db.Close(); usersCollection = Userss.GetValues(); dataGrid.Items.Refresh(); } 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(); } } Update时,我更改的值会在Button中更新,但如果我尝试删除或添加一行更新不会发生在database中。 注意:我已尝试使用databaseDataSets并且无效(我相信是因为我将Adapters放入ComboBoxes。 任何想法我可以在代码中更改什么?

2 个答案:

答案 0 :(得分:0)

您必须在DataGrid中实现特定事件。 例如:

if let intVal = Int(textView.text) {
    ... intVal from text is valid
} else {
    ... text does not represent an int - e.g. it's empty
}

所以在你的代码背后:

<DataGrid ItemsSource="{Binding Userss.UserCol, Mode=TwoWay, 
          UpdateSourceTrigger=PropertyChanged}"
          DataContext="{Binding RelativeSource={RelativeSource Self}}"
          RowEditEnding="DataGrid_RowEditEnding">

删除非常相似:

将此添加到xlmns:

private void DataGrid_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e)
{
    // Only act on Commit
    if (e.EditAction == DataGridEditAction.Commit)
    {
        //execute your update SQL
    }
}

所以在你的数据网格中:

xmlns:ic="clr-namespace:System.Windows.Input;assembly=PresentationCore" 

在代码隐藏中:

<DataGrid 
    ItemsSource="{Binding Userss.UserCol, Mode=TwoWay, 
                     UpdateSourceTrigger=PropertyChanged}"
        DataContext="{Binding RelativeSource={RelativeSource Self}}"
        RowEditEnding="DataGrid_RowEditEnding"
        ic:CommandManager.PreviewExecuted="DataGrid_OnPreviewExecuted">

答案 1 :(得分:0)

您只为数据库中的更新数据提供更新命令,但不提供插入和删除命令。尝试以相同的方式使用SQLiteDataAdapter:

if (Meteor.isServer) {
  Meteor.methods({
    execute(params) {
      //...
    }
  });
}