How to update selected row values in datagridview?

I've been trying to update the values from a sql database that's set as a data source in my windows form datagridview, but end up updating all rows instead. I've been working on creating a basic task manager app for a development course that I'm enrolled in.

I'm having a hard time figuring out where the problem is located. I think that my code may not be properly set to the selected row?

I've supplied the code below, any and all help would be appreciated. If anyone need further clarification shoot me a message on the chat. throws a thumbs up

My Current Code:

private void UpdateBtn_Click(object sender, EventArgs e)
{

    //Update button [almost done - data is not updating correctly]
    string connectionString = "Data Source =ULTRA-COMPUTER; Initial Catalog =test; Persist Security Info =True; User ID = sa; Password = 12345";
    SqlConnection con = new SqlConnection(connectionString);
    string queryStatement = "SELECT * FROM testtask";

    if (Task.Text != "" && Date.Text != "")
    {
        SqlCommand cmd = new SqlCommand(queryStatement, con);
        DataTable task = new DataTable("testtask");
        SqlDataAdapter ada = new SqlDataAdapter(cmd);

        con.Open();
        cmd.CommandText = "UPDATE [testtask] SET Task='" + Task.Text + "',Date='" + Date.Text + "' ";
        cmd.Connection = con;
        cmd.Parameters.AddWithValue("@Task", Task.Text);
        cmd.Parameters.AddWithValue("@Date", Date.Text);
        cmd.ExecuteNonQuery();
        TaskData.DataSource = task;
        MessageBox.Show("Update Inserted!");
        ClearTxt();
    }

    else
    {
        MessageBox.Show("Please Enter A Task/DueDate To Update");
    }
    con.Close();
}

Upvotes: 1

Views: 2593

Answers (2)

Zealous System
Zealous System

Reputation: 2324

First add a hidden column for the primary key of your database table in datagridview. And now when you want to update the selected row that you have edited it use that primary key in where condition of your query.

cmd.CommandText = "UPDATE [testtask] SET Task='" + Task.Text + "',Date='" + Date.Text + "WHERE [TaskId]=@TaskId";
cmd.Parameters.AddWithValue("@TaskId", TaskIdFromDatagridview);

Upvotes: 1

Inaam
Inaam

Reputation: 488

I think the problem is in this line

cmd.CommandText = "UPDATE [testtask] SET Task='" + Task.Text + "',Date='" + Date.Text + "' ";

You've not added the where clause that's why it'll update all rows in the table. You must add a where clause.

For example you've taskid as primary key in this table and want to update a task with taskid 999 then your query must be

cmd.CommandText = "UPDATE [testtask] SET Task='" + Task.Text + "',Date='" + Date.Text + "' where taskid = 999 ";

Upvotes: 0

Related Questions