简体   繁体   中英

C# MySQL Update - Datagridview

In a C# Windows Form I have two buttons; Query and Update. On that form is a datagridview where I put my MySQL results. In separation, when I click Query I get the results correctly. When I change a value in the datagrid and click Update, MySQL receives those updates. However, when I return to click Query to get the latest changes from MySQL table, the datagridview is blank. I have to close the form and re-click Query for it to finally appear.

Is this a function of not calling the da.update() correctly or referencing something incorrectly in the Query button?

Here is the code from the winform:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using System.Data.Odbc;
using System.Data.SqlClient;

namespace GridAdjustments
{
    public partial class Form3 : Form
    {
        private MySqlDataAdapter da;        // Data Adapter
        private DataSet ds;                 // Dataset
        private string sTable = "Portfolio";  // Table Name

        public Form3()
        {
            InitializeComponent();
        }


        private void Query_Click(object sender, EventArgs e)
        {
            string connectionString = "SERVER=localhost;" +
                                      "UID=xxxxxx;" +
                                      "PASSWORD=xxxxx;" +
                                      "DATABASE=test";

            MySqlConnection conn = null;

            try
            {    
                conn = new MySqlConnection(connectionString);

                conn.Open();
                da = new MySqlDataAdapter("SELECT * FROM books;", conn);
                ds = new DataSet();
                da.Fill(ds, sTable);
                conn.Close(); 
            }
            catch (MySql.Data.MySqlClient.MySqlException ex)
            {
                MessageBox.Show(ex.Message);
                conn.Close();
            }
            finally
            {
                dataGridView1.Refresh();

                dataGridView1.DataSource = ds;
                dataGridView1.DataMember = sTable;

            }  
        }


        private void Update_Click(object sender, EventArgs e)
        {
            MySqlCommandBuilder cmb = new MySqlCommandBuilder(da);

            da.Update(ds, sTable);
        }
    }
}

Try changing you code, and check if it works for you.

private void Query_Click(object sender, EventArgs e)
{
    try
    {    
        MySqlConnection conn = new MySqlConnection(connectionString);
        conn.Open();
        da = new MySqlDataAdapter("SELECT * FROM books;", conn);
        ds = new DataSet();
        da.Fill(ds, sTable);
        conn.Close(); 
    }
    catch (MySql.Data.MySqlClient.MySqlException ex)
    {
        MessageBox.Show(ex.Message);            
    }
    finally
    {
        dataGridView1.Refresh();

        dataGridView1.DataSource = ds;
        dataGridView1.DataMember = sTable;

        if (conn.State == System.Data.ConnectionState.Open)
            conn.Close();
    }  
}

private void Update_Click(object sender, EventArgs e)
{
    try
    { 
        MySqlConnection conn = new MySqlConnection(connectionString);
        conn.Open();

        MySqlCommandBuilder cmb = new MySqlCommandBuilder(da);
        cmb.Connection = conn;
        da.Update(ds, sTable);
    }
    catch (MySql.Data.MySqlClient.MySqlException ex)
    {
        MessageBox.Show(ex.Message);            
    }
    finally
    {           
        if (conn.State == System.Data.ConnectionState.Open)
            conn.Close();
    }  
}

Your approach works for simple queries as you have here - but say you wanted to have the author's URL on the form as in:

"SELECT books.*, trim(author.URL) as WebSite FROM books left join author on books.AuthorID = author.RecordID group by books.name;

I added the Trim() and AS because the MySQLConnector does not support editing more than one table at a time, and making it a calculated field works - until you want to refresh it.

For now it is something to keep in mind as I have not come up with a solution, but I keep digging.

try this one. rebind your datasource to refresh your DG after the update.

   private void Update_Click(object sender, EventArgs e)
    {
        MySqlCommandBuilder cmb = new MySqlCommandBuilder(da);

        da.Update(ds, sTable);

        dataGridView1.DataSource = ds;      

    }

Not the cleanest, but here is a working example:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data;
using MySql.Data.MySqlClient;

namespace TryMariaDB_DataGridView
{
    public partial class Form1 : Form
    {
        private MySqlDataAdapter MyDA = new MySqlDataAdapter();
        private BindingSource bSource = new BindingSource();
        private DataSet dataSet = new DataSet();
        private DataTable table = new DataTable();

        public Form1()
        {
            InitializeComponent();
        }

        private void MySQL_ToDatagridview()
        {
            string connectionString = "server = localhost; userid = root; database = BirdWatching; port = 3306; password = xxxxxx";
            MySqlConnection mysqlCon = new MySqlConnection(connectionString);
            mysqlCon.Open();

            //select command has to include the primary key column, otherwise update command will fail
            //as it does not know exactly what row is updated.
            MyDA.SelectCommand = new MySqlCommand("SELECT * from bird", mysqlCon);
            MyDA.Fill(table);   
            bSource.DataSource = table;
            dataGridView1.DataSource = bSource;
        }

        private void buttonSubmit_Click(object sender, EventArgs e)
        {
            //calling the command builder will generate an update command for you
            MySqlCommandBuilder cb = new MySqlCommandBuilder(MyDA);
            MyDA.Update(table);
        }

        private void buttonReload_Click(object sender, EventArgs e)
        {
            table.Clear();
            MySQL_ToDatagridview();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            MySQL_ToDatagridview();
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM