How to set multiple selections in ASP.NET ListBox? - asp.net

I can't find a way to select multiple items in an ASP.NET ListBox in the code behind? Is this something needs to be done in Javascript?

You will have to use FindByValue method of the ListBox
foreach (string selectedValue in SelectedValuesArray)
{
lstBranch.Items.FindByValue(selectedValue).Selected = true;
}

Here's a C# sample
(aspx)
<form id="form1" runat="server">
<asp:ListBox ID="ListBox1" runat="server" >
<asp:ListItem Value="Red" />
<asp:ListItem Value="Blue" />
<asp:ListItem Value="Green" />
</asp:ListBox>
<asp:Button ID="Button1"
runat="server"
onclick="Button1_Click"
Text="Select Blue and Green" />
</form>
(Code Behind)
protected void Button1_Click(object sender, EventArgs e)
{
ListBox1.SelectionMode = ListSelectionMode.Multiple;
foreach (ListItem item in ListBox1.Items)
{
if (item.Value == "Blue" || item.Value == "Green")
{
item.Selected = true;
}
}
}

this is the VB code to do so...
myListBox.SelectionMode = Multiple
For each i as listBoxItem in myListBox.Items
if i.Value = WantedValue Then
i.Selected = true
end if
Next

In C#:
foreach (ListItem item in ListBox1.Items)
{
item.Attributes.Add("selected", "selected");
}

I like where bill berlington is going with his solution. I don't want to iterate through the ListBox.Items for each item in my array. Here is my solution:
foreach (int index in indicesIntArray)
{
applicationListBox.Items[index].Selected = true;
}

Related

Asp.net - Postback loses Dropdownlist index

I have a simple Dropdownlist control that JS handles,
once the index changes, a div is opened/closed.
html code for initializing the Dropdownlist-
<select id="selectmethod" onchange="run()">
<option value="1" selected="selected">option1</option>
<option value="2" >option2</option>
</select>
JavaScript code to handle OnChange event-
function run() {
var e = document.getElementById("selectmethod");
var value = e.options[e.selectedIndex].value;
if (value == 1) {
$('#changecourseitems').slideUp();
$('#addnewcourseitems').slideDown();
}
if (value == 2) {
$('#addnewcourseitems').slideUp();
$('#changecourseitems').slideDown();
}
Now when the user clicks on an <ASP:LinkButton ... />
a Postback event starts and the Dropdownlist index resets (so as the hidden div).
How can I maintain the Dropdownlist index after the Postback ?
Thanks!
To maintain the contents of the dropdownlist you either have to re-populate it on the server every time or use viewstate. For example you can populate the data once like this
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DropDownList1.Items.Add(new ListItem() { Text = "option1", Value = "1", Selected = true });
DropDownList1.Items.Add(new ListItem() { Text = "option2", Value = "2" });
}
}
and in the page you can use an ASP control and enable view state:
<asp:DropDownList ID="DropDownList1" runat="server" EnableViewState="true">
</asp:DropDownList>
Now the data will be posted back and forth and will be maintained on the client side
To maintain the value, there are multiple approaches.
1. Change the select to server control.
2. Add a hidden value and save your select tag value to this hidden value in your run(). And then set the select value
in document.ready().
<asp:HiddenField ID="yourHiddenValue" runat="server" />
Your run method.
function run() {
var e = document.getElementById("selectmethod");
var value = e.options[e.selectedIndex].value;
if (value == 1) {
$('#changecourseitems').slideUp();
$('#addnewcourseitems').slideDown();
}
if (value == 2) {
$('#addnewcourseitems').slideUp();
$('#changecourseitems').slideDown();
}
$('#<%=yourHiddenValue.ClientID%>').val(value); // <--- added
}
This is document ready function.
$(function() {
var hiddenValue = $('#<%=yourHiddenValue.ClientID%>').val();
$('#selectmethod').val(hiddenValue);
}
If you want to persist the control's state in ASP.Net Web Form, you want to use DropDownList Server Control which uses ViewState under the hood.
<asp:DropDownList runat="server" ID="DropDownList1">
<asp:ListItem Text="Add New Course" Value="1" />
<asp:ListItem Text="Change Course" Value="2" />
</asp:DropDownList>
<div id="changecourseitems">Change course</div>
<div id="addnewcourseitems">Add new course</div>
<asp:LinkButton ID="LinkButton1" runat="Server" OnClick="LinkButton1_Click"
Text="Submit" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
var selectMethod = function(){
if ($('#<%= DropDownList1.ClientID %>').val() === '1') {
$('#changecourseitems').hide();
$('#addnewcourseitems').slideDown();
} else {
$('#addnewcourseitems').hide();
$('#changecourseitems').slideDown();
}
}
$('#<%= DropDownList1.ClientID %>').change(selectMethod);
selectMethod();
});
</script>
<asp:DropDownList ID="selectmethod" ClientIDMode="Static" runat="server" EnableViewState="true">
</asp:DropDownList>
With the ClientIDMode=static you maintain the id as it is specify on the control
your js file should be:
$('#selectmethod').change(function () {
var value = $(this).val();
if (value == 1) {
$('#changecourseitems').slideUp();
$('#addnewcourseitems').slideDown();
}
if (value == 2) {
$('#addnewcourseitems').slideUp();
$('#changecourseitems').slideDown();
}
});

Select Values from two combobox from a list of combobox?

I have six combobox placed on my form and at same time i want user can select values from maximum of two combobox.
for this i have take a counter variable which get incremented every time when selectedindex of a combobox get changed but didn't reach to solution.
Can you guys explain how can i do this ?
I created an example for you. I hope it can be usefull.
ASP.Net Page:
<form id="form1" runat="server">
<div>
<div>
<label>Combobox 1</label>
<asp:DropDownList runat="server" OnSelectedIndexChanged="Unnamed1_SelectedIndexChanged" AutoPostBack="True">
<asp:ListItem>Select</asp:ListItem>
<asp:ListItem>Combo-1-1</asp:ListItem>
<asp:ListItem>Combo-1-2</asp:ListItem>
</asp:DropDownList>
</div>
<div>
<label>Combobox 2</label>
<asp:DropDownList runat="server" OnSelectedIndexChanged="Unnamed1_SelectedIndexChanged" AutoPostBack="True">
<asp:ListItem>Select</asp:ListItem>
<asp:ListItem>Combo-2-1</asp:ListItem>
<asp:ListItem>Combo-2-2</asp:ListItem>
</asp:DropDownList>
</div>
<div>
<label>Combobox 3</label>
<asp:DropDownList runat="server" OnSelectedIndexChanged="Unnamed1_SelectedIndexChanged" AutoPostBack="True">
<asp:ListItem>Select</asp:ListItem>
<asp:ListItem>Combo-3-1</asp:ListItem>
<asp:ListItem>Combo-3-2</asp:ListItem>
</asp:DropDownList>
</div>
<div>
<label>Combobox 4</label>
<asp:DropDownList runat="server" OnSelectedIndexChanged="Unnamed1_SelectedIndexChanged" AutoPostBack="True">
<asp:ListItem>Select</asp:ListItem>
<asp:ListItem>Combo-4-1</asp:ListItem>
<asp:ListItem>Combo-4-2</asp:ListItem>
</asp:DropDownList>
</div>
<div>
<label>Combobox 5</label>
<asp:DropDownList runat="server" OnSelectedIndexChanged="Unnamed1_SelectedIndexChanged" AutoPostBack="True">
<asp:ListItem>Select</asp:ListItem>
<asp:ListItem>Combo-5-1</asp:ListItem>
<asp:ListItem>Combo-5-2</asp:ListItem>
</asp:DropDownList>
</div>
<div>
<label>Combobox 6</label>
<asp:DropDownList runat="server" OnSelectedIndexChanged="Unnamed1_SelectedIndexChanged" AutoPostBack="True" Height="19px">
<asp:ListItem>Select</asp:ListItem>
<asp:ListItem>Combo-6-1</asp:ListItem>
<asp:ListItem>Combo-6-2</asp:ListItem>
</asp:DropDownList>
</div>
<div>
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
</div>
</div>
</form>
ASP.Net Code-Behind
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ViewState["DropdownSelectLimit"] = 0;
}
}
protected void Unnamed1_SelectedIndexChanged(object sender, EventArgs e)
{
if (ViewState["DropdownSelectLimit"] != null)
{
if ((int)ViewState["DropdownSelectLimit"] < 2)
{
int count = (int)ViewState["DropdownSelectLimit"];
count++;
ViewState["DropdownSelectLimit"] = count;
}
else
{
DropDownList dropDown = (DropDownList)sender;
dropDown.SelectedIndex = 0;
Label1.Text = "You can't select any option anymore";
}
}
}
If you have any question just ask me on comments :)
I created a setup for Winforms as it wasn't complete clear if you wanted it for Winforms or ASP.Net
I will not handle how you should fill a combobox, i'm sure you know how to do this, whether this is filled static or dynamic.
My solution (although quite rude) makes you link a simplified handler named HandleComboBoxSelectedIndexChanged to each combobox SelectionChanged event. This can be The SelectedItemChanged, SelectedValueChanged or SelectedIndexChanged.
Quite important: each combo needs a null value.
//will hold a list of your combobox names
private List<string> SelectedCombos;
//form load: Link the events to the correct handler
private void Form_Load()
{
foreach(var combo in Controls)
{
if(combo is ComboBox)
combo.SelectedValueChanged += HandleComboBoxSelectedIndexChanged;
}
}
//will handle the selectedIndexOrItemchanged event
private void HandleComboBoxSelectedIndexChanged(object sender, EventArgs e)
{
if(SelectedCombos = null)
SelectedCombos = new List<string>();
var combo = (ComboBox)sender;
if(combo.SelectedValue == null)
if(!SelectedCombos.Exist(combo.Name))
SelectedCombos.Remove(combo.Name);
else
if(!SelectedCombos.Exist(combo.Name) && SelectedCombos.Count < 2)
SelectedCombos.Add(combo.Name)
SetComboAvailability();
}
Another function which might be useful, whenever 2 combos are selected, make the enabled state false. This means that your user can only select from the 2 selected combos untill one of them is reset at it's null position. This way your user can only select what is possible.
//set the combos availability, less then 2 selections ok, own selection also ok else not ok
private void SetComboAvailability()
{
foreach(var combo in Controls)
{
if(combo is ComboBox)
combo.Enabled = SelectedCombos.Count < 2 || SelectedCombos.Contains(combo.Name);
}
}
Below a small example of how you could retrieve all your values from the combos based on their names.
//Something for handling all the values
private void RetrieveValues()
{
foreach(var v in SelectedCombos)
{
var combo = this.Controls.Find(v);
if(combo is ComboBox)
{
//do something with the selectedValue
var val = combo.SelectedValue; // or selecteditem
MessageBox.Show(string.Format("Control {0} has value {1}", combo.Name, val);
}
}
}
If you don't understand something feel free to ask.
Also:
the EventArgs property might change according to the selected event:
do: _comboBox1.SelectedValueChanged+= (TAB TWICE in VS) to see what the automatic code generation looks like. (always handy)
Example:
_comboBox1.SelectedValueChanged += _comboBox1_SelectedValueChanged;
private void _comboBox1_SelectedValueChanged(object sender, EventArgs e){}

Custom validator message not displaying

VS2013, WebForms, .NET 4.51
I have a FormView defined and in my EditTemplate I have as follows:
<div class="form-group">
<asp:Label ID="lblClientClassification" CssClass="col-md-2 control-label" runat="server" for="cblClientClassifications" Text="Kind"></asp:Label>
<div class="col-md-5">
<asp:CheckBoxList ID="cblClientClassifications" runat="server"></asp:CheckBoxList>
<asp:CustomValidator ID="cfvClientKinds" runat="server" Display="Dynamic" CssClass="label label-danger" ErrorMessage="XXXX" ValidationGroup="Default" OnServerValidate="cfvClientClassifications_OnServerValidate"></asp:CustomValidator>
</div>
and then in the code behind:
protected void cfvClientClassifications_OnServerValidate(object aSource, ServerValidateEventArgs aArgs)
{
CustomValidator cvCheckBoxKinds = aSource as CustomValidator;
int checkedCount = 0;
if (cvCheckBoxKinds != null)
{
CheckBoxList cblClientClassifications = GuiClientClassificationsFind();
foreach (ListItem listItem in cblClientClassifications.Items)
{
if (listItem.Selected)
{
checkedCount++;
}
}
if (checkedCount == 0)
{
aArgs.IsValid = false;
cvCheckBoxKinds.ErrorMessage = "Select client kind.";
}
}
}
The OnServerValidate is firing and I am getting to set the validator to invalid as well as setting the error message (Page.IsValid is also false as expected). However, the error text is not displaying. When I view the page source I see:
<span id="ctl00_cphMainContent_fvData_cfvClientKinds" class="label label-danger" style="display:none;">XXXX</span>
instead of the error message I set as well as the fact that it is not visible.
Has anyone got any pointers here on how to track this down? I have looked at similar questions of SO but none of the comments seem to apply. Is this related to FormView perhaps?
Try your control without the CssClass="label label-danger" bootstrap first, and use the code below to check your boxes:
protected void cfvClientKinds_ServerValidate(object aSource, ServerValidateEventArgs aArgs)
{
aArgs.IsValid = cblClientClassifications.SelectedItem != null;
cfvClientKinds.ErrorMessage = "Hey! this is a new message";
}
and I guess you call this line before you fire the above event:
protected void btnValidate_Click(object sender, EventArgs e)
{
Page.Validate();
}
In Short, I think that your problem is either related to your way of finding cblClientClassifications checkBoxList or other code that you haven't stated above.
CheckBoxList cblClientClassifications = GuiClientClassificationsFind();
I decided to try out your case and created a new webform added formview and bind it to northwind categories table then inside edititemtemplate I added a checkboxlist and populated it manually. added CustomValidator double clicked it copied your codebehind and it works for me except for the findcontrol part: GuiClientClassificationsFind();
Here is the formview:
<asp:FormView ID="FormView1" runat="server" DataKeyNames="CategoryID" DataSourceID="SqlDataSource1">
<EditItemTemplate>
...
<asp:CheckBoxList ID="cblClientClassifications" runat="server">
<asp:ListItem>Bir</asp:ListItem>
<asp:ListItem>iki</asp:ListItem>
<asp:ListItem>Üç</asp:ListItem>
<asp:ListItem>Dört</asp:ListItem>
</asp:CheckBoxList>
<asp:CustomValidator ID="cfvClientKinds" runat="server" Display="Dynamic" CssClass="label label-danger" ErrorMessage="CustomValidator" OnServerValidate="cfvClientKinds_ServerValidate"></asp:CustomValidator>
<br />
<asp:LinkButton ID="UpdateButton" runat="server" CausesValidation="True" CommandName="Update" Text="Update" />
<asp:LinkButton ID="UpdateCancelButton" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel" />
</EditItemTemplate>
</asp:FormView>
And codebehind with your code:
protected void cfvClientKinds_ServerValidate(object aSource, ServerValidateEventArgs aArgs)
{
CustomValidator cvCheckBoxKinds = aSource as CustomValidator;
CheckBoxList cblClientClassifications = (CheckBoxList)FormView1.FindControl("cblClientClassifications");
int checkedCount = 0;
if (cvCheckBoxKinds != null)
{
foreach (ListItem listItem in cblClientClassifications.Items)
{
if (listItem.Selected)
{
checkedCount++;
}
}
if (checkedCount == 0)
{
aArgs.IsValid = false;
cvCheckBoxKinds.ErrorMessage = "Select client kind.";
}
}
}
I Ali Shahrokhi's method is shorter and works as well as yours..
protected void cfvClientKinds_ServerValidate(object aSource, ServerValidateEventArgs aArgs)
{
CustomValidator cvCheckBoxKinds = aSource as CustomValidator;
CheckBoxList cblClientClassifications = (CheckBoxList)FormView1.FindControl("cblClientClassifications");
aArgs.IsValid = cblClientClassifications.SelectedItem != null;
cvCheckBoxKinds.ErrorMessage = "Select client kind.";
}
if you check as you entered edititemtemplate in formview you'll see before submitting that your customvalidators span will be there just as you mentioned that's because server hasn't sent it to the client yet somehow.

How to use ASP.NET tag in a server control?

I have a dropdown
<div>
<asp:DropDownList ID="RegistrationDropDownList" runat="server">
<asp:ListItem Value="NULL">All records</asp:ListItem>
<asp:ListItem Value="1">Submitted records</asp:ListItem>
<asp:ListItem Value="0">Non-Submitted records</asp:ListItem>
</asp:DropDownList>
</div>
I want to Show/hide <asp:ListItem Value="NULL">All records</asp:ListItem> based on a session variable
So I tried like this
<asp:DropDownList ID="RegistrationDropDownList" runat="server">
<%if (Convert.ToInt32(Session["user_level"]) == 1){ %>
<asp:ListItem Value="NULL">All records</asp:ListItem>
<%}%>
<asp:ListItem Value="1">Submitted records</asp:ListItem>
<asp:ListItem Value="0">Non-Submitted records</asp:ListItem>
</asp:DropDownList>
But I got an error
code blocks are not supported in this context
I understand I cant use code blocks on controls that have the runat="server" but removing it breaks my code behind logic.
How can I solve this problem ?
This should be done in code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack && Convert.ToInt32(Session["user_level"]) == 1)
{
RegistrationDropDownList.Items.Insert(0, new ListItem("All records", "NULL"));
}
}
Add it in the code behind
if (Convert.ToInt32(Session["user_level"]) == 1)
{
ListItem newItem = new ListItem();
newItem.Value = null;
newItem.Text = "All record";
DropDownList1.Items.Add(newItem);
}
It's a shame that ListItem doesn't have a Visibility property that you could bind to. The best solution I can think of is to write a class that extends DropDownList; add a method that inserts the "All Records" item before rendering.
public class ExtendedList : DropDownList
{
protected override void OnLoad(EventArgs e)
{
if (Convert.ToInt32(Session["user_level"]) == 1)
{
Items.Insert(0, new ListItem { Value = "NULL", Text = "All Records" });
}
}
}

Customvalidator: Check if radiobuttonlist contains a selected item

I have a radiobuttonlist with two items, Yes or No. The radiobuttonlist control has a customvalidator that needs a servervalidation function and a javascript clientvalidationfunction. Could you help me? The function in this message works but only when i actually have choosen one of the two listitems, when no listitem is selected the validation skips my radiobuttonlist control.
function ValidateRadioButtonList(source, arguments) {
var RBL = document.getElementById(source.controltovalidate);
var radiobuttonlist = RBL.getElementsByTagName("input");
var counter = 0;
var atLeast = 1
for (var i = 0; i < radiobuttonlist.length; i++) {
if (radiobuttonlist[i].checked) {
counter++;
}
}
if (atLeast = counter) {
arguments.IsValid = true;
return arguments.IsValid;
}
arguments.IsValid = false;
return arguments.IsValid;
}
EDIT: Relevant code from comments
<asp:Button ID="btnSubmit" runat="server" Text="Submit" CssClass="btnNormal"
CausesValidation="True" />
<asp:CustomValidator runat="server"
ClientValidationFunction="ValidateRadioButtonList"
OnServerValidate="RadioButtonListServerValidation" ID="cvRadioButtonList"
Font-Bold="True" Font-Size="Medium" ErrorMessage="Business critical"
ControlToValidate="rblBusinessCritical">*</asp:CustomValidator>
<asp:RadioButtonList ID="rblBusinessCritical" runat="server" RepeatLayout="Flow"
RepeatDirection="Horizontal" TabIndex="4">
<asp:ListItem Text="Yes" Value="1" />
<asp:ListItem Text="No" Value="0" />
</asp:RadioButtonList>
Code Behind:
Public Sub RadioButtonListServerValidation(ByVal sender As Object, _
ByVal args As ServerValidateEventArgs)
If rblBusinessCritical.SelectedValue = "-1" Then
args.IsValid = False
cvRadioButtonList.ErrorMessage = "Business critical needed"
Exit Sub
Else
args.IsValid = True
End If
End Sub
Have you set the ValidateEmptyText Property of the CustomValidator to true?
edit:
Have you set the CausesValidation Property of your Submit-Button/RadioButtonList to true?
Please provide some code from your aspx-page.
Here is another javascript clientvalidation function i have tried:
function ValidateRadioButtonList(source, arguments) {
var RBL = document.getElementById(source.controltovalidate);
var radio = RBL.getElementsByTagName("input");
var isChecked = false;
for (var i = 0; i < radio.length; i++) {
if (radio[i].checked) {
isChecked = true;
break;
}
}
if (!isChecked) {
alert("Please select an item");
arguments.IsValid = false;
}
arguments.IsValid = true;
}
Do you need to use client-side?
Here is a server-side solution...
<asp:RadioButtonList id="radTerms" runat="server">
<asp:listitem id="optDisagree" runat="server" value="Disagree" selected="true">I don't agree</asp:ListItem>
<asp:listitem id="optAgree" runat="server" value="Agree">I agree</asp:ListItem>
</asp:RadioButtonList>
<asp:CustomValidator Display="Dynamic" ErrorMessage="You have to agree to the terms and conditions" ID="cmpTerms" ControlToValidate="radTerms" SetFocusOnError="true" runat="server" OnServerValidate="cmpTermsAccepted_ServerValidate">*</asp:CustomValidator>
CodeBehind:
protected void cmpTermsAccepted_ServerValidate(Object source, System.Web.UI.WebControls.ServerValidateEventArgs args)
{
args.IsValid = (args.Value == "Agree");
}
That should work. Trying taking the control to validate property off the customer validator.
<asp:RadioButtonList ID="LocationAccurateRBL" CssClass="radioButtonList" RepeatDirection="Horizontal" RepeatColumns="4" RepeatLayout="Flow" runat="server">
<asp:ListItem Text="Yes" Value="1" />
<asp:ListItem Text="No" Value="0" />
</asp:RadioButtonList>
<asp:CustomValidator runat="server" ID="CheckBoxRequired" EnableClientScript="true" ControlToValidate="LocationAccurateRBL"
ClientValidationFunction="LocationAccurate_ClientValidate" ValidateEmptyText="true"
Text="*" ForeColor="Red" ErrorMessage="Please let us know if the location is accurate" SetFocusOnError="true" ValidationGroup="CreateVG" />
And the script, is much shorter because of jquery. This will do what you want.
<script>
function LocationAccurate_ClientValidate(sender, e) {
e.IsValid = $("#<%=LocationAccurateRBL.ClientID%> > input").is(':checked');
}
</script>

Resources