In this article I will explain with an example, how to update Database Table using ListBox in ASP.Net using C# and VB.Net.
Database
I have made use of the following table Hobbies with the schema as follows.
I have already inserted few records in the table.
Note: You can download the database table SQL by clicking the download link below.
HTML Markup
The HTML markup consists of following controls.
ListBox – For capturing user input.
The ListBox has been assigned with a SelectionMode property to Multiple for allowing multiple item selection.
Button – For updating database table.
The Button has been assigned with an OnClick event handler.
<b>Hobbies:</b>
<br />
<br />
<asp:ListBox ID="lstHobbies" runat="server" SelectionMode="Multiple"></asp:ListBox>
<br />
<br />
<asp:Button ID="btnUpdate" runat="server" Text="Save" OnClick="OnUpdate" />
Namespaces
You will need to import the following namespaces.
C#
using System.Data.SqlClient;
using System.Configuration;
VB.Net
Imports System.Data.SqlClient
Imports System.Configuration
Populating ListBox with records using C# and VB.Net
Inside the Page_Load event handler, first the connection is read from Web.Config file.
Then, a connection to the database is established using the SqlConnection class.
Then, using ExecuteReader method of SqlCommand class, the records are fetched from the Jobbies Table and assigned to the DataSource property of the ListBox.
Finally, the DataTextField and DataValueField are set with the Hobby and HobbyId respectively.
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
string sql = "SELECT HobbyId, Hobby FROM Hobbies";
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(sql, con))
{
con.Open();
lstHobbies.DataSource = cmd.ExecuteReader();
lstHobbies.DataTextField = "Hobby";
lstHobbies.DataValueField = "HobbyId";
lstHobbies.DataBind();
con.Close();
}
}
}
}
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Dim sql As String = "SELECT HobbyId, Hobby FROM Hobbies"
Using con As SqlConnection = New SqlConnection(constr)
Using cmd As SqlCommand = New SqlCommand(sql, con)
con.Open()
lstHobbies.DataSource = cmd.ExecuteReader()
lstHobbies.DataTextField = "Hobby"
lstHobbies.DataValueField = "HobbyId"
lstHobbies.DataBind()
con.Close()
End Using
End Using
End If
End Sub
Updating Database Table using ListBox in C# and VB.Net
When Update Button is clicked, a FOR EACH loop is executed over the ListBox items and inside the loop UpdateHobby method (explained later) is called.
UpdateHobby
Inside the UpdateHobby method, a connection to the database is established using the SqlConnection class.
Then, the HobbyId and checked status i.e. IsSelected value is passed as parameter to UPDATE query set earlier.
Finally, the record is updated using
ExecuteNonQuery function of the
SqlCommand class and the success message is displayed in
JavaScript Alert Message Box using
RegisterStartupScript method.
C#
protected void OnUpdate(object sender, EventArgs e)
{
foreach (ListItem item in lstHobbies.Items)
{
this.UpdateHobby(int.Parse(item.Value),item.Selected);
}
ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", "alert('Records successfully updated!');", true);
}
private void UpdateHobby(int hobbyId, bool isSelected)
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
string sql = "UPDATE Hobbies SET IsSelected = @IsSelected WHERE HobbyId = @HobbyId";
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(sql, con))
{
cmd.Parameters.AddWithValue("@HobbyId",hobbyId);
cmd.Parameters.AddWithValue("@IsSelected",isSelected);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
VB.Net
Protected Sub OnUpdate(sender As Object, e As EventArgs)
For Each item As ListItem In lstHobbies.Items
Me.UpdateHobby(Integer.Parse(item.Value), item.Selected)
Next
ClientScript.RegisterClientScriptBlock(Me.GetType(), "alert", "alert('Records successfully updated!');", True)
End Sub
Private Sub UpdateHobby(hobbyId As Integer, isSelected As Boolean)
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Dim sql As String = "UPDATE Hobbies SET IsSelected = @IsSelected WHERE HobbyId = @HobbyId"
Using con As SqlConnection = New SqlConnection(constr)
Using cmd As SqlCommand = New SqlCommand(sql, con)
cmd.Parameters.AddWithValue("@HobbyId",hobbyId)
cmd.Parameters.AddWithValue("@IsSelected",isSelected)
con.Open()
cmd.ExecuteNonQuery()
con.Close()
End Using
End Using
End Sub
Screenshots
Form
Records before Updating
Records after Updating
Downloads