In this article i'm going to show you how to bind data from database into listbox control in asp.net
HTML Markup Language - Add ListBox
ListBox control allows single or multiple item selection. To enable multiple item selection, set the SelectionMode
property to Multiple.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <asp:ListBox ID="ListBox1" runat="server"></asp:ListBox> </div> </form> </body> </html>
C# Coding :
C# Coding : Namespace
Adding Namespace which help to Bind data from database to application i.e SqlConnection
, SqlCommand
, SqlDataAdapter
and DataSet
.
using System.Data; using System.Data.SqlClient;
C# Coding : BindCountryListBox
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { BindCountryListBox(); } } private void BindCountryListBox() { SqlConnection conn = new SqlConnection("Data Source=.; Database=master; User ID=sa; Password=12345;"); SqlDataAdapter da = new SqlDataAdapter("select countryid, countryname from CountryTable", conn); DataSet ds = new DataSet(); da.Fill(ds); ListBox1.DataSource = ds; ListBox1.DataTextField = "countryid"; ListBox1.DataValueField = "countryname"; ListBox1.DataBind(); }
0 Komentar untuk "ListBox show data from database in asp.net"