简体   繁体   English

Datagridview单元格值更改更新数据库

[英]Datagridview cell value change update database

I have retrieved data from Mysql database into a DataGridView1. 我已经将Mysql数据库中的数据检索到DataGridView1中。 Let us suppose I am in Row 0. When I change the contents of Row 0, Cell 1 and press enter key or a button, the Update query should modify that row, but I am unable to modify the value of the cell. 让我们假设我在第0行中。当我更改第0行,单元格1的内容并按Enter键或按钮时,Update查询应该修改该行,但是我无法修改该单元格的值。 The cell maintains its previous value when i reload data and the database is not modified. 当我重新加载数据且数据库未修改时,该单元格保持其先前的值。 For example, if I change the contents of a cell under column Client_Name from "Acs" to "Gmt", how can I change the value of the cell from "Acs" to "Gmt"? 例如,如果我将Client_Name列下单元格的内容从“ Acs”更改为“ Gmt”,如何将单元格的值从“ Acs”更改为“ Gmt”? and to have it updated into Mysql database, I am using c# in Vs 2012. below is my code that retrieves my database into datagridview1 any help is welcomed thanks. 并将其更新到Mysql数据库中,我在Vs 2012中使用c#。以下是将我的数据库检索到datagridview1中的代码,欢迎任何帮助,谢谢。

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

namespace PI.Gen
{
    public partial class frmMain : Form
    {
        MySqlConnection Conn;


        public frmMain()
        {
            InitializeComponent();
            btnDisconnect.Enabled = true;
            btnLoadData.Enabled = false;
            btnLoadClients.Enabled = false;

        }





        private void btnConnect_Click(object sender, EventArgs e)
        {

            string strConnect = "server=" + txtServer.Text + ";uid=" + txtUsername.Text + ";pwd=" + txtPassword.Text + ";database=" + txtDatabase.Text;
            try
            {
                if (txtServer.TextLength <= 0 || txtUsername.TextLength <= 0 || txtDatabase.TextLength <= 0)
                {
                    MessageBox.Show("You have an empty database connection field. Please supply a valid value.");
                    return;
                }

                Conn = new MySqlConnection(strConnect);
                Conn.Open();

                if (Conn.State.ToString() != "Open")
                {
                    MessageBox.Show("Could not open database connection");
                    return;
                }
                btnDisconnect.Enabled = true;
                btnConnect.Enabled = false;
                btnLoadData.Enabled = true;
                btnLoadClients.Enabled = true;
                //  btnSubmitClient.Enabled = true;
            }
            catch (Exception ex)  // catch on general exceptions, not specific
            {
                MessageBox.Show(ex.Message);
                return;
            }
        }



        private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (Conn != null)
            {
                Conn.Close();
            }
        }

        private void btnDisconnect_Click(object sender, EventArgs e)
        {
            try
            {
                Conn.Close();
                Conn = null;
                btnDisconnect.Enabled = false;
                btnConnect.Enabled = true;
                btnLoadData.Enabled = false;
                btnLoadClients.Enabled = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }
        }





        private void btnLoadData_Click(object sender, EventArgs e)
        {
            try
            {
                string CmdString = "SELECT * FROM t_receipients";
                MySqlDataAdapter sda = new MySqlDataAdapter(CmdString, Conn);
                DataSet ds = new DataSet();

                sda.Fill(ds);
                dataGridView1.DataSource = ds.Tables[0].DefaultView;


            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }

         }


        private void btnLoadClients_Click(object sender, EventArgs e)
        {
            try
            {

                string CmdString = "SELECT * FROM t_clients";
                MySqlDataAdapter sda = new MySqlDataAdapter(CmdString, Conn);

                DataSet ds = new DataSet();
                sda.Fill(ds);
                dataGridView1.DataSource = ds.Tables[0].DefaultView;

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }

        }

After series of trials and error, i finally found what i was looking for, thus being able to update database from datagridview below is my worked around code which works 100% hope it helps someone in future, and thanks @RageComplex for helping out, but one more thing does anyone know how to implement that i mean instead of hitting the enter button to take changes in the datagridview you rather click on a button ty 经过一系列的试验和错误,我终于找到了我想要的东西,因此能够从下面的datagridview更新数据库是我的代码,可以100%希望它对将来的人有所帮助,并感谢@RageComplex的帮助,但是还有没有一件事,有人知道如何实现我的意思吗,而不是按Enter键在datagridview中进行更改,而是单击ty

   private void dataGridView1_RowValidated(object sender, DataGridViewCellEventArgs e)
    {
        try
        {
            DataTable changes = ((DataTable)dataGridView1.DataSource).GetChanges();
            if (changes != null)
            {
                MySqlCommandBuilder mcb = new MySqlCommandBuilder(mySqlDataAdapter);
                mySqlDataAdapter.UpdateCommand = mcb.GetUpdateCommand();
                mySqlDataAdapter.Update(changes);
                ((DataTable)dataGridView1.DataSource).AcceptChanges();

                MessageBox.Show("Cell Updated");
                return;
            }


        }

        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }


    }

You are not updateing your changes to the database. 您不更新对数据库的更改。 While you keep your connection open doesn't mean that this will automatically update your data. 在您保持连接打开的同时,并不意味着这将自动更新您的数据。

First of all, don't keep your connection open. 首先,不要保持连接打开。 In your app you have a connect button which is good for testing but not for really keeping the connection open, not with databases in my opinion. 在您的应用程序中,您有一个connect按钮,该按钮非常适合测试,但不适用于真正保持连接打开,我认为不适合使用数据库。

The way you load data is correct. 加载数据的方式是正确的。

You give the datagridview an DataSource which is a table from your DataSet. 您给datagridview一个数据源,它是数据集中的一个表。 So changes made in the datagridview ARE saved to your DataSet but not to your database. 因此,在datagridview中所做的更改将保存到您的DataSet中,而不保存到您的数据库中。

This is how you update your database 这是您更新数据库的方式

   public void UpdateTable(DataSet ds)
    {
        using (MySqlConnection connect = new MySqlConnection(ConnString))
        {
            connect.Open();
            MySqlDataAdapter adapt = new MySqlDataAdapter();
            MySqlCommandBuilder commbuilder = new MySqlCommandBuilder(adapt);
            adapt.SelectCommand = new MySqlCommand("SELECT * FROM t_receipients", connect);
            adapt.Update(ds.Tables[0]); 
        }
    }

Make sure, before you Update your database, you use datagridview1.EndEdit() 确保在更新数据库之前,使用datagridview1.EndEdit()

Also, you using , this will ensure a connection is closed again after completing that code, best is to always have it in a try-except. 另外, using ,这将确保在完成该代码后再次关闭连接,最好是始终将其保留在try-except中。

You had struggles with connecting the database as it appears to be in the commends. 您似乎很难连接数据库,因为它似乎值得赞扬。 I've also forgot to include MySqlDataAdapter above, I used an adapter globally in that case. 我也忘记了在上面包含MySqlDataAdapter,在这种情况下我全局使用了适配器。 I didn't want to report this question as duplicated, but now it kinda does look like this answer. 我不想将这个问题重复报告,但是现在看起来确实像这个答案。

I would like to give code which I have tested in my application.I used it for button click event. 我想提供在应用程序中测试过的代码。我将其用于按钮单击事件。

private void button3_Click(object sender, EventArgs e)
    {
        string StrQuery;
        try
        {
            string MyConnection2 = "server=localhost;user id=root;password=;database=k";
            using (MySqlConnection conn = new MySqlConnection(MyConnection2))
            {
                using (MySqlCommand comm = new MySqlCommand())
                {
                    comm.Connection = conn;
                    conn.Open();
                    for (int i = 0; i < dataGridView3.Rows.Count; i++)
                    {
                        StrQuery = @"update s set  Quantity='" + dataGridView3.Rows[i].Cells["Quantity"].Value.ToString() + "' where No='" + dataGridView3.Rows[i].Cells["Item No"].Value.ToString() + "';";

                        comm.CommandText = StrQuery;
                        comm.ExecuteNonQuery();
                    }
                }
            }
        }
        catch
        { 
        }
    }

I think it may help you 我认为这可能对您有帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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