【问题标题】:C# save changes in datagridviewC#在datagridview中保存更改
【发布时间】:2021-06-19 21:22:40
【问题描述】:

当我按下修改按钮然后进行相同的更改并在刷新后保存时,我有 DataGridView,其中的值与更改前相同。

按钮 1 - 插入新记录 按钮 2 - 刷新 DataGridView 按钮 3 - 允许更新 DataGridView 中的记录 按钮 4 - 保存更改 按钮 5 - 取消更改

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 System.Data.SqlClient;
using System.Configuration;

namespace IS
{
public partial class Form2 : Form
{
    public Form2()
    {
        InitializeComponent();
        LoadTable();

        label1.Text = "User: " + User.name + " " + User.surename;
    }

    private void label1_Click(object sender, EventArgs e)
    {

    }

    private void LoadTable()
    {
        using (SqlConnection connection = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\***\Documents\Visual Studio 2015\Projects\***\Database1.mdf;Integrated Security=True;Connect Timeout=30"))
        using (SqlCommand query = new SqlCommand("Select FirstName, LastName, Login, Email from Users", connection))
        {
            try
            {
                SqlDataAdapter Adapter = new SqlDataAdapter();
                Adapter.SelectCommand = query;

                DataTable UsersTable = new DataTable();
                Adapter.Fill(UsersTable);
                BindingSource UserTableSource = new BindingSource();

                UserTableSource.DataSource = UsersTable;
                dataGridView1.DataSource = UserTableSource;
                Adapter.Update(UsersTable);
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
    private void label1_Click_1(object sender, EventArgs e)
    {

    }

    private void UserManageToolStripMenuItem_Click(object sender, EventArgs e)
    {
        panel2.Visible = true;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Form3 form3 = new Form3();
        form3.FormClosing += new FormClosingEventHandler(this.Form3_FormClosing);
        form3.Show();
    }

    private void button2_Click(object sender, EventArgs e)
    {
        LoadTable();
    }

    private void Form3_FormClosing(object sender, FormClosingEventArgs e)
    {
        LoadTable();
    }

    private void button3_Click(object sender, EventArgs e)
    {
        dataGridView1.ReadOnly = false;
        button4.Visible = true;
        button5.Visible = true;
    }

    private void button4_Click(object sender, EventArgs e)
    {
        try
        {
            SqlDataAdapter sda = new SqlDataAdapter();
            SqlCommandBuilder scb = new SqlCommandBuilder();
            DataTable dt = new DataTable();

            scb = new SqlCommandBuilder(sda);
            sda.Update(dt);

            dataGridView1.ReadOnly = true;
            button4.Visible = false;
            button5.Visible = false;
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

    private void button5_Click(object sender, EventArgs e)
    {
        LoadTable();
        button4.Visible = false;
        button5.Visible = false;
    }
}
}

【问题讨论】:

标签: c# winforms datagridview


【解决方案1】:

这应该做你想做的。

using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        SqlCommand sCommand;
        SqlDataAdapter sAdapter;
        SqlCommandBuilder sBuilder;
        DataSet sDs;
        DataTable sTable;        

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string connectionString = "Data Source=.;Initial Catalog=pubs;Integrated Security=True";
            string sql = "SELECT * FROM Stores";
            SqlConnection connection = new SqlConnection(connectionString);
            connection.Open();
            sCommand = new SqlCommand(sql, connection);
            sAdapter = new SqlDataAdapter(sCommand);
            sBuilder = new SqlCommandBuilder(sAdapter);
            sDs = new DataSet();
            sAdapter.Fill(sDs, "Stores");
            sTable = sDs.Tables["Stores"];
            connection.Close();
            dataGridView1.DataSource = sDs.Tables["Stores"];
            dataGridView1.ReadOnly = true;
            save_btn.Enabled = false;
            dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
        }

        private void new_btn_Click(object sender, EventArgs e)
        {
            dataGridView1.ReadOnly = false;
            save_btn.Enabled = true;
            new_btn.Enabled = false;
            delete_btn.Enabled = false;
        }

        private void delete_btn_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Do you want to delete this row ?", "Delete", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                dataGridView1.Rows.RemoveAt(dataGridView1.SelectedRows[0].Index);
                sAdapter.Update(sTable);
            }
        }

        private void save_btn_Click(object sender, EventArgs e)
        {
            sAdapter.Update(sTable);
            dataGridView1.ReadOnly = true;
            save_btn.Enabled = false;
            new_btn.Enabled = true;
            delete_btn.Enabled = true;
        }
    }
}

【讨论】:

    【解决方案2】:

    所以在我的情况下,我想这样做,以便用户可以更改员工的状态并将其保存到数据源中!我将我以前的一些知识和试验与 Brad Larson 的答案结合起来,我最终做到了,这对我来说就像一个魅力!

        SqlCommand sCommand;
        SqlDataAdapter sAdapter;
        SqlCommandBuilder sBuilder;
        DataSet sDs;
        DataTable sTable;
        private void StatusEmployeeForm_Load(object sender, EventArgs e)
        {
            // TODO: This line of code loads data into the 'nestorConsultingDBDataSet.Employee' table. You can move, or remove it, as needed.
            string connectionString = your connection string
            string sql = "SELECT * FROM Employee";
            SqlConnection connection = new SqlConnection(connectionString);
            connection.Open();
            sCommand = new SqlCommand(sql, connection);
            sAdapter = new SqlDataAdapter(sCommand);
            sBuilder = new SqlCommandBuilder(sAdapter);
            sDs = new DataSet();
            sAdapter.Fill(sDs, "Employee");
            sTable = sDs.Tables["Employee"];
            connection.Close();
            employeeData.DataSource = sDs.Tables["Employee"];
        }
    
        private void saveBtn_Click(object sender, EventArgs e)
        {
            this.employeeBindingSource.EndEdit();
            this.sAdapter.Update(sTable);
            MessageBox.Show("Changes saved!");
        }
    

    请注意,您还需要插入“using.System.Data.SqlClient;”在代码的顶部,当然将 connectionString 更改为正确的连接字符串!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-28
      • 1970-01-01
      • 1970-01-01
      • 2012-07-07
      相关资源
      最近更新 更多