azzyloth
azzyloth

Reputation: 43

updating data in database using datagridview C#

I have a problem with my code regarding editing data in database using a DataGridView.

I have an error at da.update(dt); It says,

Dynamic SQL generation for the UpdateCommand is not supported against a SelectCommand that does not return any key column information.

When i change the SELECT to UPDATE/INSERT I get an error at da.fill(dt);.

What is wrong with my code?

Here's my code:

private void btnEdit_Click(object sender, EventArgs e) > {
    con.Open();
    DataTable dt = new DataTable();
    SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM RegistrationTable", con);
    da.Fill(dt);
    dt.Rows[dgvREGtable.CurrentRow.Index].BeginEdit();
    dt.Rows[dgvREGtable.CurrentRow.Index][0] = tbFirstname.Text;
    dt.Rows[dgvREGtable.CurrentRow.Index][1] = tbLastname.Text;
    dt.Rows[dgvREGtable.CurrentRow.Index][2] = tbEmail.Text;
    dt.Rows[dgvREGtable.CurrentRow.Index][3] = tbContacts.Text;
    dt.Rows[dgvREGtable.CurrentRow.Index][4] = tbUsername.Text;
    dt.Rows[dgvREGtable.CurrentRow.Index][5] = tbPassword.Text;
    dt.Rows[dgvREGtable.CurrentRow.Index].EndEdit();
    SqlCommandBuilder cb = new SqlCommandBuilder(da);
    da.Update(dt);
    displayrecords();
    con.Close();
}

Upvotes: 1

Views: 6092

Answers (2)

Wanabrutbeer
Wanabrutbeer

Reputation: 697

In my opinion, the easiest way to achieve this is to actually bind the DataGridView to your dataset, then the bindings will handle all the ugly stuff for you. For example:

DataSet mydata = new DataSet();
// populate your dataset however you like
DataBindingSource mybindingsource = new DataBindingSource(typeof(DataSet));
mybindingsource.DataSource = mydata;
DataGridView mydatagridview = new DataGridView();
mydatagridview.DataSource = mybindingsource;

Thats the nitty gritty way, but its much easier in designer to achieve this.

Upvotes: 2

user1711092
user1711092

Reputation:

Your select query needs to return the primary key of the table. If your table doesn't have a primary key, you need to set one.

Upvotes: 5

Related Questions