ListBox Asp.net Binding csharp
Here is an example of ListBox in Asp.net with C#.net. There are situation where you want to bind the DataSource and select DataValueField, DataTextField to ListBox. Even you may want to perform multiple selection and choose the values from user selection.
HTML source code of ListBox in Asp.net using C#.net
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>ListBox example</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ListBox ID="lstUsers" runat="server"></asp:ListBox></div>
</form>
</body>
</html>
Code behind with C#.net
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
BindListBox();
}
}
private void BindListBox()
{
lstUsers.DataSource = GetUserProfiles();
lstUsers.DataTextField= "UserName";
lstUsers.DataValueField = "ID";
lstUsers.DataBind();
}
private List GetUserProfiles()
{
UserInformation u1 = new UserInformation();
u1.UserName = "Satalaj1";
u1.ID = 1;
UserInformation u2 = new UserInformation();
u2.UserName = "Satalaj2";
u2.ID = 2;
UserInformation u3 = new UserInformation();
u3.UserName = "Satalaj3";
u3.ID = 3;
UserInformation u4 = new UserInformation();
u4.UserName = "Satalaj4";
u4.ID = 4;
UserInformation u5 = new UserInformation();
u5.UserName = "Satalaj5";
u5.ID = 5;
UserInformation u6 = new UserInformation();
u6.UserName = "Satalaj6";
u6.ID = 6;
UserInformation u7 = new UserInformation();
u7.UserName = "Satalaj7";
u7.ID = 7;
List lstUsers = new List();
lstUsers.Add(u1);
lstUsers.Add(u2);
lstUsers.Add(u3);
lstUsers.Add(u4);
lstUsers.Add(u5);
lstUsers.Add(u6);
lstUsers.Add(u7);
return lstUsers;
}
}
public class UserInformation
{
string _userName;
int _id ;
public string UserName
{
get{return _userName;}
set{_userName = value;}
}
public int ID
{
get{return _id;}
set{_id = value;}
}
}
Description of ListBox binding in Asp.net (C#)
GetUserProfiles method returns the mock data which is nothing but collection of User Information object. List is generic collection which can hold any data types. It requires System.Collections.Generic namespace. At Page load event we are binding the list box to User information list. The text to display is bound to Username and Value to ID. Data Text Field, Data Value Field and Data Source are the properties of List Box instance.
Currently rated 5.0 by 1 people
- Currently 5/5 Stars.
- 1
- 2
- 3
- 4
- 5