Delete the selected row of the DataGridView and update the database.

Source: Internet
Author: User

Delete the selected row of the DataGridView and update the database.

The previous article published the DataGridView control to display data. DataGridView often appears when dealing with databases and is also very useful. Using the DataGridView to modify and query databases is convenient.

Here we need to use the DataGridView data and delete the data from the database by selecting the row.

The principle is to extract the primary key of the selected record and then pass it to the entity. The object is used to pass the value to the D layer to modify the database.

The following is the code of each layer for your reference.

The interface-Layer Code is the parent class method of layer D. Only layer D code is provided here:

<Span style = "background-color: rgb (255,255,255);"> <span style = "font-family: KaiTi_GB2312; font-size: 18px; "> 'override and delete the user interface method Public Function DelUser (user As Entity. loginEntity) As Integer Implements IAddDel. delUser Dim strSQL As String = "delete from User_info where userName = @ username" Dim params () As SqlParameter = {New SqlParameter ("@ username", user. user_name)} Dim helper As New SqlHelper Dim int = helper. executeNoQuery (strSQL, CommandType. text, params) Return int End Function </span>

Abstract Factory Code:

<Span style = "background-color: rgb (255,255,255);"> <span style = "font-family: KaiTi_GB2312; font-size: 18px; "> Private Shared ReadOnly AssemblyName As String =" DAL "'declares the Assembly name Private Shared ReadOnly db As String = ConfigurationManager. appSettings ("DB") 'reads the configuration file Public Function AddDel () As IAddDel Dim className As String = AssemblyName + ". "+ db +" AddDelDAL "Dim iadddel As IAddDel iadddel = CType (Assembly. load (AssemblyName ). createInstance (className), IAddDel 'reflection Return iadddel End Function </span>

Layer B code:

<Span style = "background-color: rgb (255,255,255);"> <span style = "font-family: KaiTi_GB2312; font-size: 18px; "> 'determine whether the Public Function IsDelUser (ByVal user As Entity. loginEntity) As Boolean Dim int = iadddel. delUser (user) If int = 1 Then Return True Else Return False End If End Function </span>

U-Layer Code

<Span style = "background-color: rgb (255,255,255);"> <span style = "font-family: KaiTi_GB2312; font-size: 18px; "> Dim k As Integer = gvwUser. selectedRows. count Dim thisUser As New Entity. loginEntity Dim ub As New BLL. addDelBLL 'determines whether there is an option to record If k> 0 Then If MessageBox. show ("deleted users cannot be restored! Continue to delete? "," Prompt ", MessageBoxButtons. yesNo, _ MessageBoxIcon. question) = Windows. forms. dialogResult. yes then' is deleted from the bottom up To avoid the hourglass effect For I As Integer = k To 1 Step-1 'To get the user name thisUser. user_name = gvwUser. selectedRows (I-1 ). cells ("userName "). value. tostring' to determine whether the selected user is a logon user If thisUser. user_name = UserName Then MsgBox ("the current user cannot be deleted. Please select again! ", VbOKOnly + vbExclamation," system prompt ") Exit Sub Else If ub. IsDelUser (thisUser) = True Then MsgBox (" deleted successfully! ", VbOKOnly + vbInformation," system prompt ") Else MessageBox. Show (" deletion failed! "," System prompt ", MessageBoxButtons. OK, MessageBoxIcon. error) End If 'deletes the information deleted from the database from Datagridview1 gvwUser. rows. removeAt (gvwUser. selectedRows (I-1 ). index) End If Next End If Else MsgBox ("select the row to be deleted") Exit Sub End If End Sub </span>

The effect is as follows:

Before deletion: after deletion:






We use the DataGridView to operate data more intuitively, but the data is priceless. Be careful when operating the database! To avoid unnecessary troubles. If necessary, you should give a prompt to determine whether to delete the data or improve the operation permissions. To facilitate the operation, ensure data security!


C # What is the code for deleting the selected row and updating it in the database?

The code you have not found on the Internet ..
Let's give you a simple example.
First, you must select a row for deletion. When binding, the table ID must exist in the table or be saved with tags. For example, the first column is ID, you also need to select a row for deletion. When binding, dataGridView1.SelectionMode = DataGridViewSelectionMode. fullRowSelect; this sentence is indispensable, meaning that only one row can be selected.
Then in the button event
Private void button#click (object sender, EventArgs e)
{
SqlConnection con = new SqlConnection ("your database connection string ");
Try
{
Con. Open ();
String select_id = maid [0]. Cells [0]. Value. ToString (); // the Value of the first column of the selected current row, that is, ID
String delete_by_id = "delete from ?? Where table ID = "+ select_id; // SQL deletion statement
SqlCommand cmd = new SqlCommand (delete_by_id, con );
Cmd. EndExecuteNonQuery ();
MessageBox. Show ("deleted successfully! ");
}
Catch
{
MessageBox. Show ("Please select the correct line! ");
}
Finally
{
Con. Dispose ();
}
}

In the DataGridView datagridatagri, how do I delete the selected entire row of data while deleting the data in the database? I use SQL

The DataGridView datagriis bound to a dataset or able. You need to delete the row in the data source, bind it again, or refresh the DataGridView.
At the same time, write a statement to delete the database ~
For example:
SqlCommand cmd = new SqlCommand ();
Cmd. Connection = new SqlConnection (SQL _connect );
Cmd. CommandText = "delete from gl_card_no where card_no = '" + textBox3.Text. Trim () + "'";
If (MessageBox. Show ("are you sure you want to delete this row? "+ Cmd. CommandText +" "," prompt ", MessageBoxButtons. OKCancel, MessageBoxIcon. Question) = DialogResult. OK)
{

Try
{
Cmd. Connection. Open ();
Cmd. ExecuteNonQuery ();
Cmd. Connection. Close ();
MessageBox. Show ("deleted successfully! ");
}
Catch (Exception ee)
{
MessageBox. Show (ee. ToString ());
}
Finally
{
Cmd. Dispose ();
}
}

Related Article

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.