In this article I will explain with an example, how to use Custom
ASP.Net Server control
DropDownCheckBoxes which is a Multiple Selection
DropDownList consisting of a
CheckBoxList control within it.
Installing DropDownCheckBoxes library from Nuget
You will need to install the DropDownCheckBoxes library from Nuget Package Manager Console using the following command.
Install-Package DropDownCheckBoxes –Version 1.1.0.31568
Registering the DropDownCheckBoxes DLL
After successful installation, you will need to register the control on the page using the Register directive as shown below.
<%@ Register TagPrefix="asp" Namespace="Saplin.Controls" Assembly="DropDownCheckBoxes" %>
HTML Markup
The following HTML Markup consists of:
DropDownCheckBoxes – For display an additional
SelectAll CheckBox when set to true.
The DropDownCheckBoxes will be validated using ExtendedRequiredFieldValidator.
ExtendedRequiredFieldValidator has been specified with following properties:
ControlToValidate - Specifies the ID of the control to be validated.
Error Message - It has been specified with a string value, which will be displayed to the user when the validation fails.
Button – For submit the value.
The Button has been assigned with an OnClick event handler.
<asp:DropDownCheckBoxes ID="DropDownCheckBoxes1" runat="server" Width="180px" UseSelectAllNode="false">
<Style SelectBoxWidth="195" DropDownBoxBoxWidth="160" DropDownBoxBoxHeight="90" />
<Items>
<asp:ListItem Text="Mango" Value="1"></asp:ListItem>
<asp:ListItem Text="Apple" Value="2"></asp:ListItem>
<asp:ListItem Text="Banana" Value="3"></asp:ListItem>
</Items>
</asp:DropDownCheckBoxes>
<asp:ExtendedRequiredFieldValidator ID="ExtendedRequiredFieldValidator1" runat="server"
ControlToValidate="DropDownCheckBoxes1" ErrorMessage="Required" ForeColor="Red"></asp:ExtendedRequiredFieldValidator>
<br />
<br />
<asp:Button Text="Submit" runat="server" OnClick="Submit" />
Fetching the selected values on Server Side on Button click
When the
Submit Button is clicked, a loop is executed over the Items of the
DropDownCheckBoxes control and the selected Items are displayed using
JavaScript Alert message box.
C#
protected void Submit(object sender, EventArgs e)
{
string message = string.Empty;
foreach (ListItem item in DropDownCheckBoxes1.Items)
{
if (item.Selected)
{
message += item.Text + " " + item.Value + "\\n";
}
}
ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", "alert('" + message + "');", true);
}
VB.Net
Protected Sub Submit(sender As Object, e As EventArgs)
Dim message As String = String.Empty
For Each item As ListItem In DropDownCheckBoxes1.Items
If item.Selected Then
message += item.Text + " " + item.Value + "\n"
End If
Next
ClientScript.RegisterClientScriptBlock(Me.GetType(), "alert", "alert('" & message & "');", True)
End Sub
Screenshot
Demo
Downloads