如何使用 mysql 即可编辑数据网格在 wpf 数据网格本身中插入更新删除

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22599075/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 11:19:04  来源:igfitidea点击:

how to insert update delete within the wpf datagrid itself using mysql i.e editable datagrid

mysqlwpfdatagrid

提问by user2775321

i am doing some project for my college using wpf(c#) and mysql and need to use datagrid to display info about students once displayed the admin should be able to insert new info delete and update certain info about students .. i do not want admin to click on the row, then display data in textboxes and delete or update them from there on clicking a button ...i want to let the admin just delete from the datagrid and type on the datagrid directly over existing data and hit update and reflect that in my database. i have seen many examples but nothing is working out and this is hindering my project big time Please help me out

我正在使用 wpf(c#) 和 mysql 为我的大学做一些项目,并且需要使用数据网格来显示有关学生的信息,一旦显示管理员应该能够插入新信息删除并更新有关学生的某些信息..我不想要管理员单击该行,然后在文本框中显示数据并在单击按钮时从那里删除或更新它们......我想让管理员从数据网格中删除并直接在现有数据上键入数据网格并点击更新并反映在我的数据库中。我看过很多例子,但没有任何效果,这严重阻碍了我的项目 请帮帮我

i tried and got this working http://www.nullskull.com/a/1441/wpf-gridview-sample-to-insert-update-and-delete-records.aspx

我尝试并得到了这个工作 http://www.nullskull.com/a/1441/wpf-gridview-sample-to-insert-update-and-delete-records.aspx

but this is through textboxes i need to do it directly through datgrid i.e i need a editable datagrid

但这是通过文本框我需要直接通过 datgrid 即我需要一个可编辑的数据网格

now i get the datagrid displayed however the changes i do on datagrid like update a row or delete a row is not reflecting in the database the code i have done is as follows

现在我显示了数据网格,但是我在数据网格上所做的更改(例如更新行或删除行)没有反映在数据库中,我所做的代码如下

            using System;
            using System.Collections.Generic;
               using System.Linq;
             using System.Text;
             using System.Threading.Tasks;
             using System.Windows;
             using System.Windows.Controls;
             using System.Windows.Data;
              using System.Windows.Documents;
             using System.Windows.Input;
              using System.Windows.Media;
             using System.Windows.Media.Imaging;
             using System.Windows.Navigation;
              using System.Windows.Shapes;
               using MySql.Data;
            using MySql.Data.MySqlClient;
              using System.Data;


           namespace testdatagrid
            {

               public partial class MainWindow : Window
                   {
                    DataTable dataTable = new DataTable();
                 bool changingTitle = true; 
                   public MainWindow()
                 {
                   InitializeComponent();

        dataTable.RowChanged += new DataRowChangeEventHandler(dataTable_RowChanged);
        MessageBox.Show("hi");
    }


    void dataTable_RowChanged(object sender, DataRowChangeEventArgs e)
    {
        MessageBox.Show("hi");
        if (!changingTitle)
        {
            UpdateDBIssues();
        }
    }
    private void UpdateDBIssues()
    {
        MessageBox.Show("hi");
        MySqlConnection connection = new MySqlConnection("server=localhost;uid=deepak230890;pwd=xxxx;database=deepak230890;");
        string updateString = "UPDATE userdata SET id=?id, username=?username, password=?password, WHERE id=?id";
        MySqlCommand updateCommand = new MySqlCommand(updateString, connection);
        updateCommand.Parameters.Add("?id", MySqlDbType.Int32, 100, "id");
        updateCommand.Parameters.Add("?username", MySqlDbType.VarChar, 100, "username");
        updateCommand.Parameters.Add("?password", MySqlDbType.VarChar, 100, "password");

        MySqlParameter parameter = updateCommand.Parameters.Add("?id", MySqlDbType.Int32, 10, "id");
        parameter.SourceVersion = DataRowVersion.Original;
        MySqlDataAdapter adapter = new MySqlDataAdapter();
        adapter.UpdateCommand = updateCommand;

        string insertString = "INSERT INTO userdata (id, username, password) " +
          "VALUES (?id, ?username, ?password)";
        MySqlCommand insertCommand = new MySqlCommand(insertString, connection);
        insertCommand.Parameters.Add("?id", MySqlDbType.Int32, 10, "id");
        insertCommand.Parameters.Add("?username", MySqlDbType.VarChar, 100, "username");
        insertCommand.Parameters.Add("?password", MySqlDbType.VarChar, 100, "password");

        adapter.InsertCommand = insertCommand;

        MySqlCommand deleteCommand = new MySqlCommand("DELETE FROM userdata WHERE id=?id", connection);
        MySqlParameter delParameter = deleteCommand.Parameters.Add("?id", MySqlDbType.Int32, 10, "id");
        delParameter.SourceVersion = DataRowVersion.Original;
        adapter.DeleteCommand = deleteCommand;

        DataTable booksTable = (DataTable)((DataSourceProvider)FindResource("userdata")).Data;
        adapter.Update(booksTable);
    }

    private void DataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {

    }
}

}

}

this is the mainwindow.xaml.cs file

这是 mainwindow.xaml.cs 文件

this is the mainwindow.xaml file

这是 mainwindow.xaml 文件

                  <Window
               xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
              xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
              xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
                xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
                    mc:Ignorable="d"

               x:Name="Window"
               x:Class="testdatagrid.MainWindow"
               xmlns:local="clr-namespace:testdatagrid"
               xmlns:s="clr-namespace:System;assembly=mscorlib"
                  Title="userdata"
                Width="680" Height="814">

               <Window.Resources>
                   <ObjectDataProvider x:Key="userdata"
                 ObjectType="{x:Type local:DatabaseTable}"
                    MethodName="GetTable">
                      <ObjectDataProvider.MethodParameters>
                        <s:String>SELECT * FROM userdata</s:String>
                        <s:String>username</s:String>
                        </ObjectDataProvider.MethodParameters>
                    </ObjectDataProvider>
                </Window.Resources>
                    <Grid DataContext="{StaticResource userdata}">
                  <DataGrid x:Name="dataTablegrid" ItemsSource="{Binding Mode=OneWay}"       SelectionChanged="DataGrid_SelectionChanged" IsSynchronizedWithCurrentItem="True">    </DataGrid>

</Grid>
<!-- Code for UI -->

采纳答案by voddy

This can be done, but takes some effort. It's not straight forward, meaning you have to bind the data source with the Grid and then implement the delete, update functions. there are lot of samples on the net.

这可以做到,但需要一些努力。这不是直截了当的,这意味着您必须将数据源与 Grid 绑定,然后实现删除、更新功能。网上有很多样本。

The link asked to follow : Example link

要求遵循的链接: 示例链接

You have to do the changes on your code above;

您必须对上面的代码进行更改;

  1. In the main window constructor do the following

    public MainWindow()
    {
        InitializeComponent();
        DataTable dataTable = (DataTable((DataSourceProvider)FindResource("userdata")).Data;
        dataTable.RowChanged += new DataRowChangeEventHandler(dataTable_RowChanged);
        dataTable.RowDeleted += new DataRowChangeEventHandler(dataTable_RowChanged);
    }
    
  2. In the rowchanged event;

    private void dataTable_RowChanged(object sender, DataRowChangeEventArgs e)
    {
        UpdateDBIssues();
    }
    
  1. 在主窗口构造函数中执行以下操作

    public MainWindow()
    {
        InitializeComponent();
        DataTable dataTable = (DataTable((DataSourceProvider)FindResource("userdata")).Data;
        dataTable.RowChanged += new DataRowChangeEventHandler(dataTable_RowChanged);
        dataTable.RowDeleted += new DataRowChangeEventHandler(dataTable_RowChanged);
    }
    
  2. 在 rowchanged 事件中;

    private void dataTable_RowChanged(object sender, DataRowChangeEventArgs e)
    {
        UpdateDBIssues();
    }
    

I am not sure why you do this check (!changingTitle), In your case it seems not necessary because you haven't used a combo box or a list to change the population of the Grid as is in the example. I tested the code and it works. So with these changes, you will be fine. If it still does not work, Take one command at a time and debug to catch the error. Hope this helps.

我不知道你为什么做这个检查(!变化标题),在你的情况下似乎没有必要,因为你没有使用组合框或列表来改变网格的人口,如示例中所示。我测试了代码并且它有效。所以有了这些变化,你会没事的。如果它仍然不起作用,一次执行一个命令并调试以捕获错误。希望这可以帮助。

XAML: something similar to

XAML:类似于

 <Grid DataContext="{StaticResource dataTable}">
    <DataGrid  ItemsSource="{Binding Mode=OneWay}" AutoGenerateColumns="False" IsSynchronizedWithCurrentItem="True"
                x:Name="testDataGrid" Margin="0,0,0,0" HorizontalAlignment="Center">

      <DataGrid.Columns>

                    <!--Databound columns-->

       </DataGrid.Columns>

    </DataGrid>
</Grid>