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

后端 未结 2 551
孤独总比滥情好
孤独总比滥情好 2021-01-02 07:35

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

相关标签:
2条回答
  • 2021-01-02 08:07

    as mentioned DataAdapters are one of the easy ways.

    See: http://www.codeproject.com/KB/database/relationaladonet.aspx

    for a pretty simple example that I think covers what youu need.

    0 讨论(0)
  • 2021-01-02 08:17

    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);
            }
    
        }
    }
    
    0 讨论(0)
提交回复
热议问题