Reputation: 2760
<asp:ListBox ID="lst_newGrpMembers"
DataValueField="Name"
SelectionMode="Multiple"
Width="120px"
ToolTip="Press ctrl to select multiple users"
runat="server">
</asp:ListBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1"
runat="server"
ControlToValidate="lst_newGrpMembers"
ErrorMessage="Atleast one member required"
CssClass="Error"
Text="*Atleast one member required"
ValidationGroup="CreateGroupValidationGroup">
</asp:RequiredFieldValidator>
I have a required field validator for a list box, it validates and shows error where there is no entry in the list box, but when I add item to the list box, it still shows error. When I select the list box item which I added and click submit it works fine. How to validate the list box.
Upvotes: 4
Views: 15888
Reputation: 46077
On the RequiredFieldValidator
, try setting InitialValue
to empty string:
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
InitialValue=""
ControlToValidate="lst_newGrpMembers"
ErrorMessage="Atleast one member required"
CssClass="Error"
Text="*Atleast one member required"
ValidationGroup="CreateGroupValidationGroup">
</asp:RequiredFieldValidator>
Upvotes: 11
Reputation: 894
The problem is that it is validating whether or not there is a SELECTED value in ListBox. When you post it, probably, you will only receive the selected value for the ListBox. When you add the items to the ListBox, set the SELECTED property to true, and disable the ListBox to avoid unselection.
Like this:
ListItem myItem = new ListItem();
myItem.Text = TextBox1.Text;
myItem.Selected = true;
ListBox1.Items.Add(myItem);
Hope it helps.
Upvotes: 0
Reputation: 30162
The contents of a list box are not sent to the server, only the selected item is. This is the way forms work in HTTP. Select your item after adding it or put it in a hidden form field (via script) to get sent to the server.
There are various ways to go about this via script. I did find this contro (I havent used it though) which I believe does this for you: http://www.metabuilders.com/Tools/DynamicListBox.aspx
This is also covered in more detail here: http://forums.asp.net/t/1687079.aspx/1 where they select items on postback using jQuery:
function save() {
$("#lstFiles").each(function () {
$("#lstFiles option").attr("selected", "selected");
});
return true;
}
Upvotes: 0