C # deleting rows in a table

Source: Internet
Author: User

Delete a row and use the datarow. Delete () method. The Delete () method does not perform the delete operation, but only marks the row to be deleted. Use the update method to confirm deletion.

 

Using System. Data. sqlclient;

Namespace Deleteingdata
{
Public   Partial   Class Form1: Form
{
Public Form1 ()
{
Initializecomponent ();
// Delete button event
Btndelete. Click + =   New Eventhandler (btndelete_click );
Showdata ();
}

String Sconnection =   " Data Source = Scott; initial catalog = northwind; persist Security info = true; user id = sa; Password = sa123 " ;
Dataset dsset =   New Dataset ();
Sqldataadapter sdaadapter =   Null ;
Sqlcommandbuilder scbbuilder =   Null ;

///   <Summary>
/// Show table data
///   </Summary>
Private   Void Showdata ()
{
// Establish connection
Sqlconnection scconnection =   New Sqlconnection (sconnection );
// CREATE Command
Sqlcommand sccommand = Scconnection. createcommand ();
Sccommand. commandtext =   " Select customerid, companyName from MERs " ;
// Create Adapter
Sdaadapter =   New Sqldataadapter (sccommand );

// This object is used to generate SQL statements used to update the database. You do not have to create these statements yourself
scbbuilder = New sqlcommandbuilder (sdaadapter);

// get data
sdaadapter. fill (dsset, " MERs " );
dgvview. datasource = dsset. tables [ " MERs " ];
}< br>

VoidBtndelete_click (ObjectSender, eventargs E)
{
Delete ();
}

Private   Void Delete ()
{
Datacolumn [] dckeys =   New Datacolumn [ 1 ];
Dckeys [ 0 ] = Dsset. Tables [ " MERs " ]. Columns [ " Customerid " ];
// Set the table's primary key
Dsset. Tables [ " MERs " ]. Primarykey = Dckeys;
// Search for rows contained in a primary key
Datarow drfindrow = Dsset. Tables [ " MERs " ]. Rows. Find ( " Zaczi " );

// delete data (this method does not delete data, but only marks the row to be deleted)
drfindrow. delete ();
/// Delete
sdaadapter. update (dsset, " MERs " );

//Re-display data
Dgvview. datasource=Dsset. Tables ["MERs"];
}
}
}

 

 

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.