【问题标题】:How to update MySql Database from DataGrid on C#?如何从 C# 上的 DataGrid 更新 MySql 数据库?
【发布时间】:2018-11-04 17:58:55
【问题描述】:

我正在尝试从 DataGrid 更新 MySQL 数据库,但它不起作用。添加的数据不在数据库中,并且没有错误,为什么会出现这种情况。我已经尝试解决这个问题好几天了。

private void dtGrid_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e)
        {    
        MySqlConnection conn = DBUtils.GetDBConnection();
        string table = "brands";
        string sql = "SELECT * FROM "+table;
        MySqlDataAdapter myDataAdapter = new MySqlDataAdapter(sql, conn);
        conn.Open();
        MySqlCommandBuilder myCommandBuilder = new MySqlCommandBuilder(myDataAdapter);
        myDataAdapter.InsertCommand = myCommandBuilder.GetInsertCommand();
        myDataAdapter.UpdateCommand = myCommandBuilder.GetUpdateCommand();
        myDataAdapter.DeleteCommand = myCommandBuilder.GetDeleteCommand();
        DataSet myDataSet = new DataSet();
        myDataAdapter.Fill(myDataSet, table);
        myDataAdapter.AcceptChangesDuringUpdate = true;
        myDataAdapter.Update(myDataSet, table);
        conn.Close();
    }

【问题讨论】:

  • 您是否删除了添加内容的行?还是你错过了?我所看到的只是您使用未更改的数据集进行了更新。
  • @DanielW。如何更新它?我正在尝试从 DataGrid 在数据库中插入值
  • 你需要在调用myDataAdapter.Update之前将数据添加到myDataSet中
  • @DanielW。是怎么做到的?
  • @DanielW。我做到了,但它插入了所有数据,我只需要新的

标签: c# mysql database wpf datagrid


【解决方案1】:

@尤金

所以这里:

DataTable dt = new DataTable();
DataSet ds = new DataSet();
dt = ((DataView)dtGrid.ItemsSource).ToTable() as DataTable;
ds.Tables.Add(dt);

然后用

再次填充它
myDataAdapter.Fill(ds, table);

您正在创建一个新数据表,然后向其中添加一个现有数据表。这就是重新添加所有行的原因。

尝试将您的代码更改为。 XAML:

<Grid>
    <TabControl Height="310" HorizontalAlignment="Left" Margin="-1,-1,0,0" Name="tabControl1" VerticalAlignment="Top" Width="763">
        <TabItem Header="Brands" Name="tabBrands">
            <DataGrid ItemsSource="{Binding}" Name="dtGrid" Height="280" Width="750" BeginningEdit="dtGrid_BeginningEdit" RowEditEnding="dtGrid_RowEditEnding" AutoGenerateColumns="True" AutoGeneratingColumn="dtGrid_AutoGeneratingColumn" />               
        </TabItem>
        <TabItem Header="Later" Name="tabItem2">

        </TabItem>
    </TabControl>

</Grid>

C#

public partial class MainWindow : Window
{

    private MySqlDataAdapter myDataAdapter;        
    private DataSet myDataSet;
    private MySqlCommandBuilder myBuilder;
    private MySqlConnection myConn = DBUtils.GetDBConnection();

    public MainWindow()
    {
        InitializeComponent();
        myConn.Open();
        myDataAdapter = new MySqlDataAdapter {SelectCommand=new MySqlCommand() {Connection=myConn, CommandText= "SELECT * FROM brands" } };
        myDataSet = new DataSet();
        myDataAdapter.Fill(myDataSet, "brands");           
        dtGrid.DataContext = myDataSet.Tables["brands"].DefaultView;
    }

    private void dtGrid_BeginningEdit(object sender, DataGridBeginningEditEventArgs e)
    {
        myBuilder  = new MySqlCommandBuilder(myDataAdapter);
        DataRowView myDRV = (DataRowView)dtGrid.SelectedItem;
        myDRV.BeginEdit();
    }

    private void dtGrid_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e)
    {
        DataRowView myDRV = (DataRowView)dtGrid.SelectedItem;
        myDRV.EndEdit();
        myDataAdapter.UpdateCommand = myBuilder.GetUpdateCommand();
        myDataAdapter.Update(myDataSet, "brands");
    }

    private void dtGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
    {
        var tc = e.Column as System.Windows.Controls.DataGridTextColumn;
        var b = tc.Binding as System.Windows.Data.Binding;

        b.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
        b.ValidatesOnDataErrors = true;
        b.NotifyOnValidationError = true;
    }

}

这会丢失按钮,但您现在无需按钮即可编辑和添加行。要添加一行,请转到 DataGrid 底部的空白行。

【讨论】:

  • 非常感谢,您的代码中唯一的问题是 { QuotePrefix = "[", QuoteSuffix = "]" },我更正了它并且一切正常,再次感谢您
  • 太棒了!乐意效劳。很抱歉这个错误,“[]”是 SQL 语法,我希望它与 MySQL 不同。
【解决方案2】:

一旦用户进行了编辑,您似乎正在运行此代码,名称为“RowEditEnding”。

所以我认为问题在于您只是在编辑完成后才创建MySqlCommandBuilder

您需要先创建MySqlCommandBuilder,然后进行编辑,然后获取更新/插入/删除命令。

例如类似于以下内容(对不起,在 VB 中,但你明白了要点):

Using NotesDS As New DataSet
        Using NotesDA As New SqlDataAdapter With {.SelectCommand = New SqlCommand With {.Connection = SQLDBConnection, .CommandText = "SELECT * FROM Notes WHERE ID = " & ID}}
            NotesDA.Fill(NotesDS, "Notes")
            Using NotesDV As New DataView(NotesDS.Tables("Notes"))
                Using NoteBuilder As New SqlCommandBuilder(NotesDA) With {.QuotePrefix = "[", .QuoteSuffix = "]"}                        
                    If NotesDV.Count = 1 Then                             
                        Dim NoteDRV As DataRowView = NotesDV(0)
                        NoteDRV.BeginEdit()
                        NoteDRV.Item("UserName") = UserName
                        NoteDRV.Item("Note") = Note
                        NoteDRV.Item("NoteDate") = NoteDate
                        NoteDRV.Item("CompanyCode") = CompanyCode
                        NoteDRV.EndEdit()
                        NotesDA.UpdateCommand = NoteBuilder.GetUpdateCommand
                        NotesDA.Update(NotesDS, "Notes")
                    End If
                End Using
            End Using
        End Using
    End Using

编辑

@Eugene,你的DataGrid 绑定到什么?大概您将DataView 设置为DataContext

如果是这种情况,那么您将使用DataAdapter 来填充DataView,也许是页面加载?这是您初始化MySqlCommandBuilder 所需的DataAdapter

尝试以下方法:

  • 在您的页面顶部声明您DataAdapterDataSetDataView
  • 使用 dtGrid 的 BeginningEdit 处理程序在声明的 DataAdapter 上初始化 MySqlCommandBuilder
  • 使用RowEditEnding 运行DataAdapter.Update 命令

例如(据我所知,我使用的是 SQL,但 MySQL 的工作原理相同)

using System.Windows;
using System.Windows.Controls;    
using System.Data;
using System.Data.SqlClient;

namespace testApp
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private SqlDataAdapter myDataAdapter;
        private DataView myDataView;
        private DataSet myDataSet;
        private SqlCommandBuilder myBuilder;
        private SqlConnection myConn = new SqlConnection("CONNECTIONSTRING");
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            myConn.Open();
            myDataAdapter = new SqlDataAdapter {SelectCommand=new SqlCommand() {Connection=myConn, CommandText="SELECT MINumber, CompanyName FROM EIncCompanies WHERE CompanyName LIKE 'Test%'" } };
            myDataSet = new DataSet();
            myDataAdapter.Fill(myDataSet, "EIncCompanies");
            myDataView = new DataView(myDataSet.Tables["EIncCompanies"]);
            dtGrid.DataContext = myDataView;
        }

        private void dtGrid_BeginningEdit(object sender, DataGridBeginningEditEventArgs e)
        {
            myBuilder  = new SqlCommandBuilder(myDataAdapter) { QuotePrefix="[", QuoteSuffix="]"};
            DataRowView myDRV = (DataRowView)dtGrid.SelectedItem;
            myDRV.BeginEdit();
        }

        private void dtGrid_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e)
        {
            DataRowView myDRV = (DataRowView)dtGrid.SelectedItem;
            myDRV.EndEdit();
            myDataAdapter.UpdateCommand = myBuilder.GetUpdateCommand();
            myDataAdapter.Update(myDataSet, "EIncCompanies");
        }

    }
}

我还在DataGrid中的绑定上设置了Mode=TwoWay, UpdateSourceTrigger=PropertyChanged

【讨论】:

    【解决方案3】:

    @Simon,我做了不同的事情,目前它插入了 dtGrid 中的所有值,而不仅仅是新值,也许我没有正确共享它。 用于填充 dbGrid:

            public MainWindow()
        {
            InitializeComponent();
            /*string sql = "SELECT * FROM brands";*/
            MySqlConnection conn = DBUtils.GetDBConnection();
            MySqlCommand cmd = new MySqlCommand("select * from brands", conn);
            conn.Open();
            DataTable dt = new DataTable();
            dt.Load(cmd.ExecuteReader());
            conn.Close();
            dtGrid.ItemsSource = dt.DefaultView;
        }
    

    用于插入新项目

            private void Insert_Click(object sender, RoutedEventArgs e)
        {
            MySqlConnection conn = DBUtils.GetDBConnection();
            string table = "brands";
            string sql = "SELECT * FROM " + table;
            MySqlDataAdapter myDataAdapter = new MySqlDataAdapter(sql, conn);
            conn.Open();
            MySqlCommandBuilder myCommandBuilder = new MySqlCommandBuilder(myDataAdapter);
            DataSet myDataSet = new DataSet();
            DataTable dt = new DataTable();
            DataSet ds = new DataSet();
            dt = ((DataView)dtGrid.ItemsSource).ToTable() as DataTable;
            ds.Tables.Add(dt);
            myDataAdapter.InsertCommand = myCommandBuilder.GetInsertCommand();
            myDataAdapter.UpdateCommand = myCommandBuilder.GetUpdateCommand();
            myDataAdapter.DeleteCommand = myCommandBuilder.GetDeleteCommand();
            myDataAdapter.Fill(ds, table);
            myDataAdapter.AcceptChangesDuringUpdate = true;
            myDataAdapter.Update(ds, table);
        }
    

    XAML

    <Window x:Class="TechD.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="TechDep" Height="390" Width="902">
    <Grid>
        <TabControl Height="310" HorizontalAlignment="Left" Margin="-1,-1,0,0" Name="tabControl1" VerticalAlignment="Top" Width="763">
            <TabItem Header="Brands" Name="tabBrands">
                <DataGrid AutoGenerateColumns="True" Height="280" Name="dtGrid" Width="750" CanUserAddRows="True" ItemsSource="{Binding}" RowEditEnding="dtGrid_RowEditEnding" />
            </TabItem>
            <TabItem Header="Later" Name="tabItem2">
    
            </TabItem>
        </TabControl>
        <Button Content="Insert" Height="23" HorizontalAlignment="Left" Margin="774,21,0,0" Name="Insert" VerticalAlignment="Top" Width="90" Click="Insert_Click" />
        <Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="774,50,0,0" Name="button2" VerticalAlignment="Top" Width="90" />
        <Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="774,79,0,0" Name="button3" VerticalAlignment="Top" Width="90" />
        <Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="774,108,0,0" Name="button4" VerticalAlignment="Top" Width="90" />
    </Grid>
    

    【讨论】:

      猜你喜欢
      • 2014-04-11
      • 1970-01-01
      • 1970-01-01
      • 2013-12-25
      • 1970-01-01
      • 1970-01-01
      • 2013-06-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多