如何从c#上的datagrid更新mysql数据库?

nsc4cvqm  于 2021-06-18  发布在  Mysql
关注(0)|答案(3)|浏览(423)

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

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();
    }
g6baxovj

g6baxovj1#

看起来您正在运行此代码,只要用户已按名称进行了编辑 RowEditEnding ".
所以我认为问题是你只是在创造 MySqlCommandBuilder 编辑完成后。
你需要创建 MySqlCommandBuilder 首先,进行编辑,然后获取更新/插入/删除命令。
e、 g.类似于以下内容(在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

编辑
@尤金,你的工作是什么 DataGrid 一定要吗?想必你正在设定一个 DataView 作为 DataContext ?
如果是这样的话,那么你将使用 DataAdapter 填充 DataView 在页面加载上?这就是 DataAdapter 你需要初始化你的 MySqlCommandBuilder 与。
请尝试以下操作:
宣布你 DataAdapter , DataSet 以及 DataView 在页面顶部。
使用 BeginningEdit dtgrid的处理程序来初始化 MySqlCommandBuilder 在你宣布的 DataAdapter 使用 RowEditEnding 运行 DataAdapter.Update 命令
e、 g.(据我所知,我使用的是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");
        }

    }
}

我还设置了 Mode=TwoWay, UpdateSourceTrigger=PropertyChanged 论图书馆的装订 DataGrid .

vsnjm48y

vsnjm48y2#

@尤金
所以这里:

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底部的空白行添加行。

r1zk6ea1

r1zk6ea13#

@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>

相关问题