Use sqlcommandbuilder to automatically update the datagridview

Source: Internet
Author: User

Note: This method is only applicable to a single table.
Private sqldataadapter adapter = NULL;
Private sqlcommandbuilder builder = NULL;
Private dataset = NULL;
Private sqlconnection connection = NULL;

Private void btnsave_click (Object sender, eventargs E)
{
// Code to modify data in dataset here
// Dataset. Tables [0]. Rows [0] [2] = 9; // modifications made on the datagridview interface are automatically updated to dataset.

Builder. getupdatecommand ();

// Without the sqlcommandbuilder this line wocould fail
Int COUNT = Adapter. Update (dataset, "Table1 ");
}

Private void btnquery_click (Object sender, eventargs E)
{
Connection = new sqlconnection ("Server = 10.138.141.84; uid = sa; Password = sa; database = mytest ");

Adapter = new sqldataadapter ();
Adapter. selectcommand = new sqlcommand ("select * From Table1 where id1 = 1", connection );
Builder = new sqlcommandbuilder (adapter );

Connection. open ();

// Generate the Chinese name of the column
Adapter. tablemappings. Add ("Table1", "Table1 ");
Adapter. tablemappings [0]. columnmappings. Add ("id1", "user ");
Adapter. tablemappings [0]. columnmappings. Add ("ID2", "name ");
Adapter. tablemappings [0]. columnmappings. Add ("Val", "Age ");

Dataset = new dataset ();
Adapter. fill (dataset, "Table1"); // The fill method must contain the second parameter; otherwise, the adapter. update (dataset, "Table1") will prompt that the table "Table1" cannot be found"

This. datagridview1.datasource = dataset. Tables [0];

// Return dataset;
}

Unfortunately, this method currently only supports single-Table operations and does not support any operations related to multiple tables (including columns from different tables in the same view ).

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.