This example shows how to limit the number of Listitems to be selected in the ListBox control.
ASPX
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
<script type="text/javascript" language="javascript">
function GetCurrentItemsSelected(obj)
{
var o = obj;
document.getElementById('<%= HiddenField1.ClientID %>').value = o;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ListBox ID="ListBox1" runat="server" AutoPostBack="True" Height="109px" SelectionMode="Multiple"
OnSelectedIndexChanged="ListBox1_SelectedIndexChanged" Width="141px">
<asp:ListItem onclick ="GetCurrentItemsSelected('0');">A</asp:ListItem>
<asp:ListItem onclick ="GetCurrentItemsSelected('1');">B</asp:ListItem>
<asp:ListItem onclick ="GetCurrentItemsSelected('2');">C</asp:ListItem>
<asp:ListItem onclick ="GetCurrentItemsSelected('3');">D</asp:ListItem>
<asp:ListItem onclick ="GetCurrentItemsSelected('4');">E</asp:ListItem>
<asp:ListItem onclick ="GetCurrentItemsSelected('5');">F</asp:ListItem>
</asp:ListBox>
<asp:HiddenField ID="HiddenField1" runat="server" />
</form>
</body>
</html>
RELEVANT CODES:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
ListBox1.ClearSelection();
}
}
protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
int count = 0;
int limit = 0;
int lastSelectedIndex = 0;
for (int i = 0; i < ListBox1.Items.Count; i++)
{
if (ListBox1.Items[i].Selected)
{
if (ViewState["CountLimit"] != null)
{
count++;
ViewState["CountLimit"] = count;
limit = (int)ViewState["CountLimit"];
}
else
{
count++;
ViewState["CountLimit"] = count;
}
if (limit > 3) // Selected Item Limit is up to 3
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "ShowBox", "alert('You are only allowed to Select 3 items!');", true);
//Get the last selected items selected when the items selected exceeds in 3
lastSelectedIndex = int.Parse(HiddenField1.Value.ToString());
//Unselect the 4th items selected
ListBox1.Items[lastSelectedIndex].Selected = false;
}
}
}
Technorati Tags:
ASP.NET,
TipsTricks