I decided to write a simple demo about this because I always encounter this issue at the forums. Basically, this demo shows how to pre select multiple list items in the ListBox control based from database value.
Assuming that we have this table definition with data below:
As you can see, the Table has a "IsSelected" boolean field which indicates that a particular employee name is selected or not. Note that in this demo, I named the Table above as "Table1".
Now lets set up our ListBox at the ASPX source. Assuming that we have this mark up below:
|
<asp:ListBox ID="ListBox1" runat="server" Height="149px" SelectionMode="Multiple" Width="113px">
<asp:ListItem>Vinz</asp:ListItem>
<asp:ListItem>Jhen</asp:ListItem>
<asp:ListItem>Chris</asp:ListItem>
<asp:ListItem>Shynne</asp:ListItem>
<asp:ListItem>Helen</asp:ListItem>
<asp:ListItem>Lilian</asp:ListItem>
<asp:ListItem>Rod</asp:ListItem>
<asp:ListItem>Chu</asp:ListItem>
</asp:ListBox>
|
Note: Since we need to pre-select multiple items in the ListBox then be sure to set the SelectionMode property of the ListBox to Multiple.
Here are the code blocks for pre-selecting the ListBox items based from the database data:
|
private DataTable GetData()
{
DataTable dt = new DataTable();
SqlConnection conn = new SqlConnection(GetConnectionString());
string sqlStatement = "SELECT * FROM Table1";
try
{
conn.Open();
SqlCommand sqlCmd = new SqlCommand(sqlStatement, conn);
SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);
sqlDa.Fill(dt);
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Fetch Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
}
return dt;
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DataTable dt = GetData();
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
bool isSelected = Convert.ToBoolean(dt.Rows[i]["IsSelected"]);
if (isSelected)
{
ListBox1.Items[i].Selected = true;
}
}
}
}
}
|
As you can see the code above was pretty self explanatory and straight forwad.
You can see the page output below:

That's it! Hope you will find this example useful!