Set Enable False ListItems - asp.net

I have a RadioButtonList and ListItems attached to the RadioButtonList how can I set enable=false the ListItem on code behind cus I don't have id??
<asp:RadioButtonList ID="rblSearchMode" runat="server" RepeatDirection="Horizontal">
<asp:ListItem Text="By Location" Selected="True" Value="0" onclick="searchModeClick();"></asp:ListItem>
<asp:ListItem Text="By Name" Value="1" onclick="searchModeClick();"></asp:ListItem>
</asp:RadioButtonList>

To disable an item, find it using FindByText or FindByValue, then set the item's 'Enabled' property: -
var item = rblSearchMode.Items.FindByText("By Location");
if (item != null)
{
item.Enabled = false;
}

Related

Custom validation javascript function always returns the drop down list's selected value as 0

On my page I have a text box that uses a custom validator:
<asp:CustomValidator ID="cv_Question" ControlToValidate="tb_Question" runat="server" ErrorMessage="*" OnServerValidate="ValidateQuestion" ClientValidationFunction="CheckQuestion" ForeColor="#FF0000" ValidationGroup="CreateUser"></asp:CustomValidator>
The client side validation script that I would like to use always returns 0 for the drop down list SelectedValue, even when the drop down list index has already changed.
I set the drop down list default index to 0 with !Page.IsPostBack
Here is the drop down list:
<asp:DropDownList ID="ddl_Question" runat="server" EnableViewState="true" AutoPostBack="true" onselectedindexchanged="ddl_Question_SelectedIndexChanged">
<asp:ListItem Selected="False" Text="Select a question" Value="0"></asp:ListItem>
<asp:ListItem Selected="False" Text="What was the first movie I ever saw?" Value="1"></asp:ListItem>
<asp:ListItem Selected="False" Text="What is the middle name of my oldest child?" Value="2"></asp:ListItem>
<asp:ListItem Selected="False" Text="In what city was my father born?" Value="3"></asp:ListItem>
<asp:ListItem Selected="False" Text="Who was my favourite cartoon character as a child?" Value="4"></asp:ListItem>
<asp:ListItem Selected="False" Text="What is my mother's middle name?" Value="5"></asp:ListItem>
<asp:ListItem Selected="False" Text="In what year did I meet my significant other?" Value="6"></asp:ListItem>
<asp:ListItem Selected="False" Text="What was my first pet's name?" Value="7"></asp:ListItem>
<asp:ListItem Selected="False" Text="First name of the maid of honour at my wedding?" Value="8"></asp:ListItem>
<asp:ListItem Selected="False" Text="First name of my best friend in elementary school?" Value="9"></asp:ListItem>
<asp:ListItem Selected="False" Text="Name of my all-time favourite movie character?" Value="10"></asp:ListItem>
<asp:ListItem Selected="False" Text="Create a question" Value="11"></asp:ListItem>
</asp:DropDownList>
Here is the client side validation:
<script type="text/javascript" language="javascript">
function CheckQuestion(sender, args)
{
var Question = args.Value.toString();
<% if(Convert.ToInt32(ddl_Question.SelectedValue) == 11)
{ %>
if (Question != "" && Question != null)
{
args.IsValid = true;
return;
}
else
{
args.IsValid = false;
return;
}
<% }
else
{ %>
alert(<%= Convert.ToInt32(ddl_Question.SelectedValue)%>);
args.IsValid = true;
return;
<% } %>
}
</script>
I only want to validate the tb_Question if the user has selected "Create a question" from the ddl_Question.
EDIT:
Here is my SelectedIndexChanged method. The tb_Question is made visible when the user selects "Create a question". This happens before any validation occurs.
protected void ddl_Question_SelectedIndexChanged(object sender, EventArgs e)
{
if (Convert.ToInt32(ddl_Question.SelectedValue) == 11)
{
Question.Visible = true;
}
else
{
Question.Visible = false;
}
}
Well my recommendation is to use simple JavaScript
So instead of doing that, use JavaScript and maybe jQuery like this
jQuery Nuget: https://nuget.org/packages/jQuery
<script type="text/javascript" src="Scripts/jquery-1.7.2.min.js"></script>
<script type="text/javascript" language="javascript">
function CheckQuestion(sender, args)
{
var Question = args.Value.toString();
var questionID = '<%= this.ddl_Question.ClientID %>';
var currentQuestion = $("#" + questionID).val();
if (currentQuestion == '11')
{
if (Question != "" && Question != null)
{
args.IsValid = true;
return;
}
else
{
args.IsValid = false;
return;
}
}
else
{
alert(currentQuestion);
args.IsValid = true;
return;
}
}
</script>
The issue is more likely in the Convert.ToInt32 call since this utility method returns zero when the value passed to it is null (you can check MSDN to validate this. http://msdn.microsoft.com/en-us/library/sf1aw27b.aspx) The SelectedValue property is very likely null at this point even though the selected index is zero. Try setting the SelectedValue programmatically and see I that makes any difference.

vb.net radio button list check if selected

I have the following:
<asp:RadioButtonList ID="rbIsRep" runat="server" RepeatDirection="horizontal" >
<asp:ListItem Value="1" >Yes</asp:ListItem>
<asp:ListItem Value="0" >No</asp:ListItem>
</asp:RadioButtonList>
how do I check if the radiobuttonlist has any selected items?
Use the SelectedIndex proprty to check if anything is selected and the SelectedItem property to get the selected item's text:
If rbIsRep.SelectedIndex > - 1 Then
Dim selectedItemsText = "You selected: " & rbIsRep.SelectedItem.Text
End If
You can change the selection programmatically for example with the SelectedValue property.
rbIsRep.SelectedValue = "0"
or declaratively from aspx
<asp:RadioButtonList ID="rbIsRep" runat="server" RepeatDirection="horizontal" >
<asp:ListItem Value="1" >Yes</asp:ListItem>
<asp:ListItem Selected="True" Value="0" >No</asp:ListItem>
</asp:RadioButtonList>
One way to do it:
var hasSelection = yourRadioButtonList.SelectedIndex != -1;
And for VB.NET:
Dim hasSelection = yourRadioButtonList.SelectedIndex <> -1

ASP.NET - Control dropdownlist postback programmatically

I have two dropdownlists on my form-ddl1 and ddl2. They together determine the visibility of a textbox -txt1. For that I do this check:
if (ddl1.SelectedIndex==2 && ddl2.SelectedIndex>2)
{
if (!txt1.Visible)
{txt1.Visible=true;// And then I want to call postback}
}
else
{
if (txt1.Visible)
{txt1.Visible=false;// And then I want to call postback}
}
As you can see, I want to post the page to server only if the above condions are true. The code above is triggered on SelectedIndexChanged event of the both dropdownlists. How can I or is it possible to achieve upon a condition?
I am not sure if i understand your problem but you want to achieve postback only if certain condition is met. you can hook up a javascript function on both dropdown onchange="return onchange();" Set Autopostback = true;
function Onchange() {
var ddl1 = document.getElementById('<%= ddl1.ClientID %>');
var ddl2 = document.getElementById('<%= ddl2.ClientID %>');
var txtbox = document.getElementById('<%= txtbox.ClientID %>');
if (ddl1.selectedIndex == 2 && ddl2.selectedIndex > 2) {
txtbox.style.display = "inline";
__doPostBack(ddl1, '');
}
else {
txtbox.style.display = "none";
return false;
}
}
Aspx code should look like this.
<asp:DropDownList runat="server" AutoPostBack="true" ID="ddl1" onchange="return Onchange();"
OnSelectedIndexChanged="ddl1_SelectedIndexChanged">
<asp:ListItem Text="text1" />
<asp:ListItem Text="text2" />
<asp:ListItem Text="text3" />
<asp:ListItem Text="text4" />
</asp:DropDownList>
<asp:DropDownList runat="server" AutoPostBack="true" ID="ddl2" onchange="return Onchange();"
OnSelectedIndexChanged="ddl1_SelectedIndexChanged">
<asp:ListItem Text="text1" />
<asp:ListItem Text="text2" />
<asp:ListItem Text="text3" />
<asp:ListItem Text="text4" />
</asp:DropDownList>
<asp:TextBox runat="server" ID="txtbox" />
Tested it and it works...
If AutoPostBack = True, which it would have to be for your events to be firing just call a funciton when your condition is met. ASP.NET is always posting back, you just need to handle the condition, otherwise you have to handle the validation with JavaScript and manually post the page:
if (ddl1.SelectedIndex==2 && ddl2.SelectedIndex>2)
{
if (!txt1.Visible)
{
txt1.Visible=true;// And then I want to call postback
//dowork
}
}
else
{
if (txt1.Visible)
{
txt1.Visible=false;// And then I want to call postback
//do work
}
}

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>

DataBound CheckBoxList

I have a website programmed in Asp.Net and use a ListView for displaying data. The data is coming from a LinqDataSource.
In my EditItemTemplate I have a CheckBoxList which consist of:
<asp:CheckBoxList runat="server" ID="TypeCheckBoxList" RepeatColumns="2">
<asp:ListItem Value="128">6.-10. klasse<br />Norddjurs vejleder</asp:ListItem>
<asp:ListItem Value="64">6.-10. klasse<br />Syddjurs vejleder</asp:ListItem>
<asp:ListItem Value="32">Gået ud af skolen<br/>Norddjurs vejleder</asp:ListItem>
<asp:ListItem Value="16">Gået ud af skolen<br/>Syddjurs vejleder</asp:ListItem>
<asp:ListItem Value="8">Ekstra støtte<br/>Norddjurs vejleder</asp:ListItem>
<asp:ListItem Value="4">Ekstra støtte<br />Syddjurs vejleder</asp:ListItem>
<asp:ListItem Value="2">Kontakt</asp:ListItem>
<asp:ListItem Value="1">Om os<br />Medarbejdere</asp:ListItem>
</asp:CheckBoxList>
I have a column called Type in my db and it is a tinyint. Therefore I can say (byte)Eval("Type").
But how do I databind my Eval("Type") to the CheckBoxList so if Eval("Type") is 3, then the two last items are selected?
I have tried setting a hidden value which binds to Type and then in the CheckBoxList OnLoad setting the selected items. But that did'nt work.
That's the way to do it, with the hidded value binding to Type, but on the ItemDataBound event of the ListView.
So the event would look something like this:
protected void ListViewId_ItemDataBound (object sender, ListViewItemEventArgs e)
{
HiddenField hdfType = (HiddenField)e.Item.FindControl("hdfType");
CheckBoxList TypeCheckBoxList = (HiddenField)e.Item.FindControl("TypeCheckBoxList");
// and you put the hidden just for EditItem and do:
if (hdfType != null)
foreach (ListItem item in TypeCheckBoxList.Items)
if (int.Parse(item.Value) < int.Parse(hdfType.Value))
item.Selected = true;
}
(I wrote all of this from my head, so there might be some small mistakes)
First you should write a javascript function like this
function Selected(value,type)
{
if(value<type)
return true;
else
return false;
}
<asp:ListItem Value="32" Selected= javascript:function Selected(32,Eval("Type"))>Gået ud af skolen<br />Norddjurs vejleder</asp:ListItem>
<asp:ListItem Value="16" Selected= javascript:function Selected(16,Eval("Type")>Gået ud af skolen<br />Syddjurs vejleder</asp:ListItem>
little bit modification may be required to finalize it..major focus on Selected attribute

Resources