简体   繁体   English

如何读写DataGridView数据到Sql Table

[英]How to read and write DataGridView data to Sql Table

I am currently working on a database system. 我目前正在数据库系统上工作。 In the system a user can search for a specific member using their ID. 在系统中,用户可以使用其ID搜索特定成员。 Searching for them filters all DataGridView results to just that specific member. 搜索它们会将所有DataGridView结果仅过滤到该特定成员。

    private void button3_Click(object sender, EventArgs e)
    {
        dataGridView1.ReadOnly = false;

        using (SqlConnection con = new SqlConnection(constring))
        {
            int id = Convert.ToInt32(textBox1.Text);
            con.Open();
            DataTable FindAaron = new DataTable();
            SqlDataAdapter adapt = new SqlDataAdapter("SELECT * FROM MembersTable WHERE MemberID =" + id, con);
            adapt.Fill(FindAaron);
            dataGridView1.DataSource = FindAaron;
            con.Close();
        }

    }

This code filters the DataGridView results down to one row from the table 'MembersTable'. 此代码将DataGridView结果从表“ MembersTable”向下过滤到一行。 The user can now physically click on the table cell and edit the data as much as they want. 用户现在可以实际单击表格单元格并根据需要编辑数据。 Once they are finished they hit a 'Save Changes' button which I want to save the changes they made, update the source table and refill the DataGridView with all the members, now with updated info. 一旦完成,他们将点击“保存更改”按钮,我要保存所做的更改,更新源表,并使用所有成员(现在包含更新的信息)重新填充DataGridView。 This is the code I have behind the 'Save Changes' button at the moment. 这是我目前在“保存更改”按钮后面的代码。

    try
        {
            //MemberClass.UpdateMember();
            this.membersTableTableAdapter.Update(mainDatabaseDataSet.MembersTable);
            dataGridView1.Refresh();
            MessageBox.Show("Details updated");
        }

        catch
        {
            MessageBox.Show("An error has occured");
        }       

This unfortunately does not update the DataGridView in the form to display all the updated data or save the data that has been edited back to the Sql table. 不幸的是,这不会更新窗体中的DataGridView来显示所有更新的数据,也不会将已编辑的数据保存回Sql表。 Have puzzled over this for a few days and can't figure out what I'm doing wrong. 对此感到困惑的几天,无法弄清楚我在做什么错。 Any and all help is much appreciated. 任何帮助都将不胜感激。

Actually there is no connection seen between membersTableTableAdapter and adapt or mainDatabaseDataSet.MembersTable and FindAaron . 其实有没有见过之间连接membersTableTableAdapteradaptmainDatabaseDataSet.MembersTableFindAaron

Try as following; 尝试如下:

//Get the changed data
DataTable changes = FindAaron.GetChanges();

if (changes != null)
{
    //Update data
    adapt.Update(changes);    
}

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

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