Hi gkoutsiv,
Refer below code.
Database
I have made use of the following table Customers with the schema as follows.
I have already inserted few records in the table.
You can download the database table SQL by clicking the download link below.
Download SQL file
HTML
<asp:Button ID="btnRemoveGroup" runat="server" Text="Remove" OnClick="btnRemoveGroup_Click" />
<asp:ListBox ID="lstMemberOf" runat="server" Width="100%" Rows="10" SelectionMode="Multiple"></asp:ListBox>
Namespaces
C#
using System.Data.SqlClient;
using System.Configuration;
VB.Net
Imports System.Data.SqlClient
Imports System.Configuration
Code
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
string query = "SELECT Name, CustomerId FROM Customers";
this.BindListBox(lstMemberOf, query, "Name", "CustomerId");
}
}
protected void BindListBox(ListBox lst, string query, string text, string value)
{
string constring = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand(query, con))
{
con.Open();
lstMemberOf.DataSource = cmd.ExecuteReader();
lstMemberOf.DataTextField = text;
lstMemberOf.DataValueField = value;
lstMemberOf.DataBind();
con.Close();
}
}
}
VB.Net
Partial Class VB
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Dim query As String = "SELECT Name, CustomerId FROM Customers"
Me.BindListBox(lstMemberOf, query, "Name", "CustomerId")
End If
End Sub
Protected Sub BindListBox(ByVal lst As ListBox, ByVal query As String, ByVal text As String, ByVal value As String)
Dim constring As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As SqlConnection = New SqlConnection(constring)
Using cmd As SqlCommand = New SqlCommand(query, con)
con.Open()
lstMemberOf.DataSource = cmd.ExecuteReader()
lstMemberOf.DataTextField = text
lstMemberOf.DataValueField = value
lstMemberOf.DataBind()
con.Close()
End Using
End Using
End Sub
Protected Sub btnRemoveGroup_Click(ByVal sender As Object, ByVal e As EventArgs)
For Each item As ListItem In lstMemberOf.Items
If item.Selected Then
Dim customerId As String = item.Value.ToString()
Dim constring As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As SqlConnection = New SqlConnection(constring)
Using cmd As SqlCommand = New SqlCommand("DELETE FROM Customers WHERE CustomerId = @CustomerId", con)
cmd.Parameters.AddWithValue("@CustomerId", customerId)
con.Open()
cmd.ExecuteNonQuery()
con.Close()
End Using
End Using
End If
Next
Dim query As String = "SELECT Name, CustomerId FROM Customers"
Me.BindListBox(lstMemberOf, query, "Name", "CustomerId")
End Sub
End Class
Screenshot