0

I watched a video tutorial and reprogrammed the same code. I have noticed that a didn´t understand, why I have to use the SqlCommandBuilder for updating a table.

    SqlDataAdapter sda;
    SqlCommandBuilder scb;
    DataTable dt;

    private void button2_Click(object sender, EventArgs e)
    {
        scb = new SqlCommandBuilder(sda);

        sda.Update(dt);
    }

I never use the variable scb. But when I comment out the scb = new SqlCommandBuilder(sda), then I get an error message:

"System.InvalidOperationException: A valid update command is required for an update."

Can someone explain, what function the CommandBuilder has?

In the remarks of the documentation it says:

The SqlCommandBuilder registers itself as a listener for RowUpdating events that are generated by the SqlDataAdapter specified in this property.

But I don´t understand when the CommandBuilder steps into action?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • The SQL command need four queries for an update : Select, Update, Insert, Delete. The command builder take an existing Select query and creates the other three. – jdweng Jan 25 '17 at 10:32
  • 1
    You don't need either. Most people use ORMs or SqlCommand to execute commands directly. – Panagiotis Kanavos Jan 25 '17 at 10:32
  • The `SqlCommandBuilder` just creates sql queries for select,update,insert and delete, and puts them into the `SqlDataAdapter` properties. You may not use it and do something like `sda.UpdateCommand.CommandText=` – Pikoh Jan 25 '17 at 10:33
  • 1
    @Pikoh In the debugger, updatecommand is null, even after execution of the sda.Update(dt); When exactly does it create the sql queries? – Mr. Tambay Jan 25 '17 at 10:49
  • Well,you are right,i was trying to "simplfy" it. In fact, as the documentation says, it subscribes to the `RowUpdating` event of the `SqlDataAdapter` and it creates the other queries then – Pikoh Jan 25 '17 at 10:55
  • Anyway, i've never used it. In my opinion.it's better to add your own queries to have a better control. – Pikoh Jan 25 '17 at 10:58
  • @Pikoh thank you for the good explanation. It sounds very logical. Is there any file, like a designer, where i can see the subscription to the `RowUpdating` event? – Mr. Tambay Jan 25 '17 at 11:55
  • I don't understand @Mr.Tambay. What do you want to see? Source code of `RowUpdating`? What handlers are subscripted to `RowUpdating` in runtime? Or what are the generated queries by `SqlCommandBuilder? – Pikoh Jan 25 '17 at 12:00
  • @Pikoh I want to see what handlers are subscribed to RowUpdating in runtime. Is this possible? – Mr. Tambay Jan 25 '17 at 12:16
  • I don't know why would you want to do that, but see [this question](http://stackoverflow.com/a/660489/579895) – Pikoh Jan 25 '17 at 12:27

0 Answers0