Delete Selected Item From ListBox And Database In ASP.NET

This article explains the following:

  • How to bind the ListBox from the database.
  • How to delete selected item from ListBox as well as in the database.

Database Chamber

Use the following table and Stored Procedure to demonstrate this concept.

  1. Create table Mas_Employee  
  2. (    
  3.     Id int primary key identity(1,1),    
  4.     Name varchar(50)  
  5. )    
  6.   
  7. --To get all the employees  
  8. Create Procedure USP_Select_Mas_Employee    
  9. @Id int = null    
  10. AS    
  11. Begin    
  12.     Select E.Id, E.Name    
  13.     From Mas_Employee E    
  14.     Where Id = Isnull(@Id, Id)    
  15. End   
  16.   
  17. --To Insert employee details  
  18. Create Procedure USP_Insert_Mas_Employee  
  19. @Name varchar(50)   
  20. AS    
  21. Begin    
  22.     Insert into Mas_Employee(NameValues(@Name)    
  23. End   
  24.   
  25. --To Delete employee details  
  26. Create Procedure USP_Delete_Mas_Employee    
  27. @Id int    
  28. AS    
  29. Begin    
  30.     Delete From Mas_Employee    
  31.     where Id=@Id    
  32. End   
Application Chamber

To create the project -
  • Go to Start, then All Programs and click Microsoft Visual Studio 2010.
  • Go to File, New, Project..., Visual C# , Web. Then select ASP.NET Empty Web Application.
  • Provide the project a name and specify the location.

Web.Config:

Create the connection string in the Web.Config file as in the following code snippet:

  1. <connectionStrings>  
  2.    <add name="conStr"  
  3.    connectionString="Password= 1234; User ID=sa; Database=DB_CsharpCorner; Data Source=."  
  4.    providerName="System.Data.SqlClient"/>  
  5. </connectionStrings>  
Next: Right-click on Solution Explorer and add a web form to your project.

Webform Design:

Design you Webform (.aspx page) as in the following:
  1. <form id="form1" runat="server">  
  2.         <div style="width: 100%;" align="center">  
  3.             <fieldset style="width: 40%;">  
  4.                 <legend>Delete Selected item from ListBox and Database</legend>  
  5.                 <table style="width: 100%;">  
  6.                     <tr>  
  7.                         <td>  
  8.                             Name:  
  9.                         </td>  
  10.                         <td>  
  11.                             <asp:TextBox ID="txtEmpName" runat="server"></asp:TextBox>  
  12.                         </td>  
  13.                         <td>  
  14.                             <asp:Button ID="btnAdd" runat="server" Text="Add" OnClick="btnAdd_Click" />  
  15.                         </td>  
  16.                     </tr>  
  17.                     <tr>  
  18.                         <td colspan="3" style="text-align:center;">  
  19.                             <asp:Label ID="lblMsg" runat="server"></asp:Label>  
  20.                         </td>  
  21.                     </tr>  
  22.                     <tr>  
  23.                           
  24.                         <td colspan="2">  
  25.                             <asp:ListBox ID="lstEmployee" runat="server"></asp:ListBox>  
  26.                         </td>  
  27.                         <td>  
  28.                             <asp:Button ID="btnDelete" runat="server" Text="Delete Selected Item" OnClick="btnDelete_Click" />  
  29.                         </td>  
  30.                     </tr>  
  31.                 </table>  
  32.             </fieldset>  
  33.         </div>  
  34.     </form>  
CodeBehind:

Add the following namespaces:
  1. using System.Data;  
  2. using System.Data.SqlClient;  
  3. using System.Configuration;  
  4. using System.Drawing;  
Invoke the ConnectionString from Web.Config as in the following:
  1. SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString);  
User Defined Functions:
  1. #region User Defined Methods  
  2.   
  3. //To Clear the fields  
  4. private void Clear()  
  5. {  
  6.     txtEmpName.Text = string.Empty;  
  7.     lblMsg.Text = string.Empty;  
  8. }  
  9.   
  10. //To bind listBox from Database  
  11. private void BindListBox()  
  12. {  
  13.     SqlDataAdapter adp = new SqlDataAdapter("USP_Select_Mas_Employee", con);  
  14.     adp.SelectCommand.CommandType = CommandType.StoredProcedure;  
  15.     DataSet ds = new DataSet();  
  16.     adp.Fill(ds);  
  17.     if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)  
  18.     {  
  19.         lstEmployee.DataSource = ds;  
  20.         lstEmployee.DataValueField = "Id";  
  21.         lstEmployee.DataTextField = "Name";  
  22.         lstEmployee.DataBind();  
  23.     }  
  24. }  
  25.   
  26. //To delete the selected item from Database  
  27. private void DeleteSelectedItem(int Id)  
  28. {  
  29.     SqlCommand cmd = new SqlCommand("USP_Delete_Mas_Employee", con);  
  30.     cmd.CommandType = CommandType.StoredProcedure;  
  31.     cmd.Parameters.AddWithValue("@Id", Id);  
  32.     if (con.State == ConnectionState.Closed)  
  33.     {  
  34.         con.Open();  
  35.     }  
  36.     int result = cmd.ExecuteNonQuery();  
  37.     if (result > 0)  
  38.     {  
  39.         Clear();  
  40.         //BindListBox();  
  41.         lblMsg.Text = "Employee deleted successfully";  
  42.         lblMsg.ForeColor = Color.Green;  
  43.     }  
  44. }  
  45.   
  46. //To add the employee from textbox to listBox  
  47. private void AddEmployee(string Name)  
  48. {  
  49.     SqlCommand cmd = new SqlCommand("USP_Insert_Mas_Employee", con);  
  50.     cmd.CommandType = CommandType.StoredProcedure;  
  51.     cmd.Parameters.AddWithValue("@Name", Name);  
  52.     if (con.State == ConnectionState.Closed)  
  53.     {  
  54.         con.Open();  
  55.     }  
  56.     int result = cmd.ExecuteNonQuery();  
  57.     if (result > 0)  
  58.     {  
  59.         Clear();  
  60.         BindListBox();  
  61.         lblMsg.Text = "Employee added successfully";  
  62.         lblMsg.ForeColor = Color.Green;  
  63.     }  
  64. }  
  65.  
  66. #endregion  
Page Event Handlers:
  1. #region Page Event Handlers  
  2.   
  3. protected void Page_Load(object sender, EventArgs e)  
  4. {  
  5.     lblMsg.Text = string.Empty;  
  6.     if (!Page.IsPostBack)  
  7.     {  
  8.         BindListBox();  
  9.     }  
  10. }  
  11.   
  12. protected void btnAdd_Click(object sender, EventArgs e)  
  13. {  
  14.     if (txtEmpName.Text.ToString() != string.Empty || txtEmpName.Text.ToString() != null)  
  15.         AddEmployee(txtEmpName.Text.ToString());  
  16.     else  
  17.     {  
  18.         lblMsg.Text = "Please provide the Name";  
  19.         lblMsg.ForeColor = Color.Red;  
  20.         return;  
  21.     }  
  22. }  
  23.   
  24. protected void btnDelete_Click(object sender, EventArgs e)  
  25. {  
  26.     if (Convert.ToInt32(lstEmployee.SelectedValue) < 0)  
  27.     {  
  28.         lblMsg.Text = "Please select an item";  
  29.         lblMsg.ForeColor = Color.Red;  
  30.         return;  
  31.     }  
  32.     else  
  33.     {  
  34.         for (int i = lstEmployee.Items.Count - 1; i >= 0; i--)  
  35.         {  
  36.             if (lstEmployee.Items[i].Selected)  
  37.             {  
  38.                 DeleteSelectedItem(Convert.ToInt32(lstEmployee.Items[i].Value));  
  39.                 lstEmployee.Items.Remove(lstEmployee.Items[i]);  
  40.             }  
  41.         }  
  42.     }  
  43. }  
  44. #endregion  
Output:

Enter the name and click on Add.

Enter the name

Then the output will be as in the following screenshot:

output

Select the ListBox Item and click Delete Selected Item button then it will be Deleted in ListBox as well as in the database.

Select the ListBox

I hope you enjoyed this article. Please provide your valuable suggestions and feedback to make this article much reliable. 

Up Next
    Ebook Download
    View all
    Learn
    View all