Populate a ListBox from two dimensional array
TwoDimensionArrayListBox.aspx
<%@ Page Language="C#" %>
<!DOCTYPE html>
<script runat="server">
protected void Button1_Click(object sender, System.EventArgs e)
{
string[,] favoriteColors = { { "Cornsilk", "#FFF8DC" }, { "Crimson", "#DC143C" }, { "Cyan", "#00FFFF" }, { "DarkBlue", "#00008B" }, { "DarkCyan", "#008B8B" } };
Label1.Text = "Two dimensional String array created successfully!<br />and populates the ListBox:<br /><br />";
int rows = favoriteColors.GetUpperBound(0);
int columns = favoriteColors.GetUpperBound(1);
ListBox1.Items.Clear();
for (int currentRow = 0; currentRow <= rows; currentRow++)
{
ListItem li = new ListItem();
for (int currentColumn = 0; currentColumn <= columns; currentColumn++)
{
if (currentColumn == 0)
{
li.Text = favoriteColors[currentRow, currentColumn];
}
else
{
li.Value = favoriteColors[currentRow, currentColumn];
}
}
ListBox1.Items.Add(li);
}
}
protected void ListBox1_SelectedIndexChanged(object sender, System.EventArgs e) {
Label2.Text = "You selected:";
Label2.Text += "<br />Item Text: "+ ListBox1.SelectedItem.Text;
Label2.Text += "<br />Item Value: " + ListBox1.SelectedItem.Value;
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>How to populate ListBox from two dimension string array in asp.net</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2 style="color:Green">asp.net array example:<br />Two Dimension String Array And ListBox</h2>
<asp:Label
ID="Label1"
runat="server"
Font-Size="Large"
ForeColor="SlateBlue"
Font-Bold="true"
Font-Italic="true"
>
</asp:Label>
<asp:Label
ID="Label2"
runat="server"
Font-Size="Large"
ForeColor="SeaGreen"
Font-Bold="true"
Font-Italic="true"
>
</asp:Label>
<br /><br />
<asp:ListBox
ID="ListBox1"
runat="server"
BackColor="DodgerBlue"
ForeColor="FloralWhite"
OnSelectedIndexChanged="ListBox1_SelectedIndexChanged"
AutoPostBack="true"
>
</asp:ListBox>
<br /><br />
<asp:Button
ID="Button1"
runat="server"
OnClick="Button1_Click"
Font-Bold="true"
Text="Populate ListBox With Two Dimensional Array"
ForeColor="Crimson"
/>
</div>
</form>
</body>
</html>