Alex February 2016

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. Searching for them filters all DataGridView results to just that specific member.

    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'. 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. 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. 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.

Answers


Irshad February 2016

Actually there is no connection seen between membersTableTableAdapter and adapt or mainDatabaseDataSet.MembersTable and FindAaron.

Try as following;

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

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

Post Status

Asked in February 2016
Viewed 2,762 times
Voted 5
Answered 1 times

Search




Leave an answer