1

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();
}

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.