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

时间:2014-03-24 00:25:38

标签: mysql wpf datagrid

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

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

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

现在我显示了datagrid然而我在datagrid上做的更改比如更新行或删除行没有反映在数据库中 我所做的代码如下

            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)
    {

    }
}

}

这是mainwindow.xaml.cs文件

这是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 -->

1 个答案:

答案 0 :(得分:0)

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

链接要求遵循: Example link

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

  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();
    }
    
  3. 我不确定为什么要进行此检查(!changingTitle),在您的情况下,似乎没有必要,因为您没有使用组合框或列表来更改网格的填充,如示例中所示。我测试了代码,它的工作原理。所以通过这些改变,你会没事的。如果它仍然不起作用,请一次执行一个命令并进行调试以捕获错误。希望这会有所帮助。

    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>
    
相关问题