Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Issue: How do I save changes made in a DataGridView back to the DataTable used?

I get a DataTable from a DataSet and then bind that DataTable to a DataGridView. Once the user edits the information on the DataGridView how do I take those changes and put them back into a DataTable that was used that I can then put back into my DataSet?

I want to make a Save Button on my DataGrid that when pressed actually saves the changes.

I don't if I can get anymore specific than that, because it is a fairly simple question.

Thanks in advance!

Let me know if you need me to elaborate more.

like image 371
OneShot Avatar asked Feb 06 '09 12:02

OneShot


1 Answers

If you are using data-binding to a DataGridView, then you are already updating the DataTable / DataSet. If you mean changes down to the database, then that is where adapters come into play.

Here's an example:

using System;
using System.Data;
using System.Linq;
using System.Windows.Forms;
static class Program
{
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();

        DataSet set = new DataSet();
        DataTable table = set.Tables.Add("MyTable");
        table.Columns.Add("Foo", typeof(int));
        table.Columns.Add("Bar", typeof(string));

        Button btn;
        using (Form form = new Form
        {
            Text = "DataGridView binding sample",
            Controls =
            {
                new DataGridView {
                    Dock = DockStyle.Fill,
                    DataMember = "MyTable",
                    DataSource = set
                },
                (btn = new Button {
                    Dock = DockStyle.Bottom,
                    Text = "Total"
                })
            }
        })
        {
            btn.Click += delegate
            {
                form.Text = table.AsEnumerable().Sum(
                    row => row.Field<int>("Foo")).ToString();
            };
            Application.Run(form);
        }

    }
}
like image 144
Marc Gravell Avatar answered Oct 05 '22 23:10

Marc Gravell