This seems like a reasonably common question, however the equally common solutions don't appear to work. Essentially the required validation control of the drop-down menu isn't firing. The drop down is populated dynamically, the code that populates the drop-down is shown at the bottom of the page.
<asp:DropDownList ID="Event" runat="server"DataTextField="EventTime" ValidationGroup="DD"
DataValueField="EventID" SelectMethod="GetEvents" AppendDataBoundItems="true" AutoPostBack="true">
<asp:ListItem Text="Select..." Value="-1" /></asp:DropDownList>
<asp:RequiredFieldValidator ID="RequiredFieldEvent" runat="server" ControlToValidate="Event"
Display="Dynamic" ValidationGroup="DD" InitialValue="-1" AutoPostback="true"
ErrorMessage="Please select a time"></asp:RequiredFieldValidator>
Code Behind:
public IQueryable<Event> GetEvents([QueryString("bikeID")] int? bikeId)
{
var _db = new WLL.DAL.Context();
IQueryable<Event> query = _db.Events;
if (bikeId.HasValue && bikeId > 0)
{
query = query.Where(b => b.BikeID == bikeId);
}
else
{
query = null;
}
return query;
}
Set InitialValue = "0" .This worked for me when -1 did not work.
Related
I have requirement where users are redirected youtube.com by using hyperlink control using below
I want to change the URL dynamically based on drop down list selected item by using below code.
protected void ddlPType_SelectedIndexChanged(object sender, EventArgs e)
{
int x = ddlPType.SelectedIndex;
if (x == 0)
{
activateCerts.NavigateUrl = "http://www.youtube.com/watch?v=3AYoipyqOkQ";
activateCerts.Text = "activateCerts";
activateCerts.Target = "_blank";
//activateCerts.HRef = "http://www.youtube.com/watch?v=3AYoipyqOkQ";
}
else if (x == 1)
{
//activateCerts.Target = "_blank";
//activateCerts.HRef = "http://www.youtube.com/watch?v=hk3hxUuwg0w";
activateCerts.Text = "activateCerts";
activateCerts.NavigateUrl = "http://www.youtube.com/watch?v=3AYoipyqOkQ";
}
and this is the one aspx code
<asp:Label runat="server" style="padding-left:23rem;" Text="pls watch this video on How to"></asp:Label>
<asp:HyperLink ID="activateCerts" runat="server"></asp:HyperLink>
but when I click on link I am not able to open a youtube video
This is working for me by setting AutoPostBack=true for dropdpwn ddlPType :
<form id="form1" runat="server">
<div>
<asp:DropDownList runat="server" ID="ddlPType" AutoPostBack="true" OnSelectedIndexChanged="ddlPType_SelectedIndexChanged">
<asp:ListItem Text="Option 1" Selected="True" />
<asp:ListItem Text="Option 2" />
</asp:DropDownList>
<br />
<asp:Label ID="Label1" runat="server" style="padding-left:23rem;" Text="pls watch this video on How to"></asp:Label>
<asp:HyperLink ID="activateCerts" runat="server"></asp:HyperLink>
</div>
</form>
.cs Page :
protected void ddlPType_SelectedIndexChanged(object sender, EventArgs e)
{
int x = ddlPType.SelectedIndex;
if (x == 0)
{
activateCerts.NavigateUrl = "http://www.youtube.com/watch?v=3AYoipyqOkQ";
activateCerts.Text = "activateCerts";
activateCerts.Target = "_blank";
//activateCerts.HRef = "http://www.youtube.com/watch?v=3AYoipyqOkQ";
}
else if (x == 1)
{
//activateCerts.Target = "_blank";
//activateCerts.HRef = "http://www.youtube.com/watch?v=hk3hxUuwg0w";
activateCerts.Text = "activateCerts";
activateCerts.NavigateUrl = "http://www.youtube.com/watch?v=3AYoipyqOkQ";
}
}
For your Dropdownlist named ddlPType, you need to make sure its AutoPostBack is true. You can set it in the Attribute Panel, or using the code:
<asp:DropDownList runat="server" ID="ddlPType" AutoPostBack="true" OnSelectedIndexChanged="ddlPType_SelectedIndexChanged">
By this step you should achieve your goal, but sometimes this is not that simple. You may need to make sure you put your data-bind (if there is) in if (!Page.IsPostBack) in Page_Load.
Also, Dropdownlist will only send data when the data is changed. That is to say, if you get two options sharing the same value, Dropdownlist may not respond you. For example:
if(!IsPostBack)
{
for(int i=0;i<10;i++)this.DropDownList1.Items.Add(new ListItem(i.ToString(),"same_value"));
}
Here comes the most strange situation: you have done all above but it still does not work. Sometimes it happens in IE8. If you use window.showModalDialog() to show DropDownList, submitting will leads you to a new page. You need to add between head tag:
<base target=_self></base>
Hope my experience will do help.
I have a drop down list with multiple values. I have a list item named "Other". When selecting other I want to generate a text box with required field validator. I have written like this:
Markup:
<asp:DropDownList ID="dl_test_name" runat="server"
OnSelectedIndexChanged="SelectedIndexChanged"
Height="22px" Width="103px">
<asp:ListItem>Science</asp:ListItem>
<asp:ListItem>Maths</asp:ListItem>
<asp:ListItem>Other</asp:ListItem>
</asp:DropDownList>
<asp:TextBox ID="tb_other" runat="server" Width="94px" Visible="False">
</asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator7" runat="server"
ControlToValidate="tb_other" ErrorMessage="*">
</asp:RequiredFieldValidator>
Code-behind:
protected void SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList dropDownList = (DropDownList)sender;
if (dropDownList.SelectedValue == "Other")
{
tb_other.Enabled = true;
tb_other.Text = string.Empty;
tb_other.Visible = true;
}
else
{
tb_other.Enabled = false;
tb_other.Text = dropDownList.SelectedValue;
}
}
but when selecting on any list item ,control doesn't go to SelectectedIndexChanged event. Only after reloading the page does it work.
What is the problem?
To make your DropDownList post back to the server you need to use the AutoPostback property, like this:
<asp:DropDownList ID="dl_test_name" runat="server"
OnSelectedIndexChanged="SelectedIndexChanged"
Height="22px" Width="103px" AutoPostBack="true">
Arathy, make AutopostBack property of dropdown to true in aspx
I have Grid with DropDownList and it has static data. It is being saved perfectly. But, while editing, I need to get SelectedValue of the DropDown from the DataBase.
My code is:
<asp:TemplateField ItemStyle-HorizontalAlign="Center" HeaderText="Order">
<ItemTemplate>
<asp:DropDownList ID="ddlOrder" SelectedValue='<%# (DataBinder.Eval(Container.DataItem,"Order")) %>' runat="server" Width="60">
<asp:ListItem Text="1" Value="1"></asp:ListItem>
<asp:ListItem Text="2" Value="2"></asp:ListItem>
<asp:ListItem Text="3" Value="3"></asp:ListItem>
<asp:ListItem Text="4" Value="4"></asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
And:
protected void gvServicePort_RowDataBound(object sender , GridViewRowEventArgs e)
{
//DropDown
if (e.Row.RowType == DataControlRowType.DataRow)
{
var dropdownList = (DropDownList)e.Row.FindControl("ddlOrder");
for (int i = 1; i < 15; i++)
{
dropdownList.Items.Add(i.ToString());
}
dropdownList.SelectedValue =
Convert.ToString(DataBinder.Eval(e.Row.DataItem, "Order"));
}
}
It is throwing and error that say that 'ddlOrder' has a SelectedValue which is invalid because it does not exist in the list of items.
Can anyone help?
Test that the value exists in your DropDownList before attempting to assign.
if (dropdownList.Items.FindByValue(value) != null)
{
// go ahead and assign
dropdownList.SelectedValue = value;
}
else
{
// handle the issue if necessary
}
I have had occasions where the value did exist in the list but setting SelectedValue was unpredictable and still resulted in the "does not exist in the list" error you mentioned. If you finding this is the case you may want to try one of the following options for assigning the selected item.
Use the FindByValue method:
dropdownList.Items.FindByValue(value).Selected = true;
or this one:
dropdownList.SelectedIndex = dropdownList.Items.IndexOf(dropdownList.Items.FindByText(value));
I always forget how to implement these last two snippets but I was able to find them both in this SO question: How to programatically set SelectedValue of Dropdownlist when it is bound to XmlDataSource.
I have the following mark-up:
<asp:DropDownList ID="ddlTownships" DataTextField="Name" AutoPostBack="True" AppendDataBoundItems="True" DataValueField="Id" runat="server" OnSelectedIndexChanged="ddlTownships_SelectedIndexChanged">
<asp:ListItem Value="0" Text="Please select a township"></asp:ListItem>
</asp:DropDownList>
and this is the code behind:
protected void ddlRegions_SelectedIndexChanged(object sender, EventArgs e)
{
var townshipDAO = (TownshipDAO)FactoryDAO.getInstance().getDAOByType(DAOEnum.Township);
ddlTownships.DataSource = townshipDAO.getAllTownshipsByRegionId(Int64.Parse(ddlRegions.SelectedValue));
ddlTownships.DataBind();
liTownships.Visible = true;
liSettlements.Visible = false;
divPhasesConsole.Visible = false;
liNumberOfStands.Visible = false;
divFirstDelimiter.Visible = false;
}
Basically whenever a user selects an item from the ddlRegion, I get all townships with the regionId selected and repopulate the dropdownlist. However the ddlTownships remembers the previously selected townships with different regions. Note that I have the property AppendDataBoundItems="True" because that was the only way I could add a list item that says "Please select a township". How can I leave the listitem defined in the mark-up and prevent the previous items from showing up after the ddl is repopulated.
Thanks for your time.
You can insert a new list item at a particular index from the code behind. So you could remove AppendDataBoundItems and add this after the databinding:
ddlTownships.Items.Insert(0, new ListItem() { Text = "Please select a township", Value = "0" });
Another helpful thing to know is that can clear out the list before databinding:
ddlTownships.Items.Clear();
I have a user control that contains 3 dropdown for(date,month, year).I have called this user control on aspx page.
Please select Date From.
On my aspx page all fields are validated with javascript validation.
when I select date from this user control (not month & year) ,and click on submit button, it shows the error message.
but my problem is that if i select year (not date,month) then in this case neither it fire the error message nor it saves the data.
I want that it fired the message everytime when atleast one field(day,month,year) is not selected.I want to handle this problem on clentside. Please give me your suggetion.
function InputValidation(vg) {
var isValid = true;
try {
var j = 0;
var inputCtrlArr = new Array();
var key = 'block';
var inputIntputArr = document.getElementsByTagName('input');
var inputDdlArr = document.getElementsByTagName('select');
var inputTextareaArr = document.getElementsByTagName('textarea');
var c = 0;
for (var i = 0; inputIntputArr.length > i; i++) inputCtrlArr[c++] = inputIntputArr[i];
for (var i = 0; inputDdlArr.length > i; i++) inputCtrlArr[c++] = inputDdlArr[i];
for (var i = 0; inputTextareaArr.length > i; i++) inputCtrlArr[c++] = inputTextareaArr[i];
for (var i = 0; inputCtrlArr.length > i; i++) {
if (inputCtrlArr[i].getAttribute('required') == 'true' && inputCtrlArr[i].getAttribute('vg') == vg) {
if (inputCtrlArr[i].value.trim() == '') {
//errinputReqCtrlArr[j++] = inputCtrlArr[i];
key = 'block';
isValid = false;
}
else {
key = 'none';
}
if (inputCtrlArr[i].type == "checkbox") {
if (inputCtrlArr[i].checked == false) {
//errinputReqCtrlArr[j++] = inputCtrlArr[i];
key = 'block';
isValid = false;
}
else {
key = 'none';
}
}
var errorDivId = inputCtrlArr[i].getAttribute('ErrorDivId');
var objErrorDivId = document.getElementById(errorDivId);
if (objErrorDivId != null) objErrorDivId.style.display = key;
}
}
}
catch (ex) { }
}
function InputCntrlValidate(obj) {
try {
if (obj.getAttribute('required') == 'true') {
if (obj.value == '') {
key = 'block';
}
else {
key = 'none';
}
var errorDivId = obj.getAttribute('ErrorDivId');
var objErrorDivId = document.getElementById(errorDivId);
if (objErrorDivId != null) objErrorDivId.style.display = key;
}
} catch (ex) { }
}
function sanitizeInput(obj) {
if (obj.getAttribute('msg') == obj.value) {
alert("same value");
}
}
The problem is in your JavaScript. Since if it is working for the one dropdownlist then it should work for other two. Further you will have to check for month and date. If it is feb then the days should be 28 or 29 and it will depend on the year. So lots of effort will require to solve it.
You only need three RequiredFieldValidators with each ControlToValidate leading to one of your DropDownLists. If you've a default value of f.e. "please select" you should set this as InitialValue of the Validators.
Here is a sample(i've only added few ListItems instead of all for dates,months and years):
<asp:DropDownlist ID="DdlDate" runat="server">
<asp:ListItem Text="please select" Enabled="true"></asp:ListItem>
<asp:ListItem Text="1"></asp:ListItem>
<asp:ListItem Text="2"></asp:ListItem>
<asp:ListItem Text="3"></asp:ListItem>
</asp:DropDownlist>
<asp:RequiredFieldValidator ID="ReqDate"
ControlToValidate="DdlDate"
InitialValue="please select"
ErrorMessage="Please select Date"
Display="Dynamic"
runat="server">
</asp:RequiredFieldValidator>
<asp:DropDownlist ID="DdlMonth" runat="server">
<asp:ListItem Text="please select" Enabled="true"></asp:ListItem>
<asp:ListItem Text="January"></asp:ListItem>
<asp:ListItem Text="February"></asp:ListItem>
<asp:ListItem Text="March"></asp:ListItem>
</asp:DropDownlist>
<asp:RequiredFieldValidator ID="ReqMonth"
ControlToValidate="DdlMonth"
InitialValue="please select"
ErrorMessage="Please select Month"
Display="Dynamic"
runat="server" >
</asp:RequiredFieldValidator>
<asp:DropDownlist ID="DdlYear" runat="server">
<asp:ListItem Text="please select" Enabled="true"></asp:ListItem>
<asp:ListItem Text="2010"></asp:ListItem>
<asp:ListItem Text="2011"></asp:ListItem>
<asp:ListItem Text="2012"></asp:ListItem>
</asp:DropDownlist>
<asp:RequiredFieldValidator ID="ReqYear"
ControlToValidate="DdlYear"
InitialValue="please select"
ErrorMessage="Please select Year"
Display="Dynamic"
runat="server" >
</asp:RequiredFieldValidator>
<asp:Button ID="BtnSubmit" runat="server" Text="submit" />
I would use the calendar control on the AjaxControlToolKit if it were me. No validation required then other than if the field is mandatory. It's a lot easier and looks a lot better. All client side.
Just down load the ajxcontrolkit dll and include in your project and use as per any custom control/third party component.
EDIT:
Ok if you just want at least one drop down to be selected then try JQuery e.g.
function isDropDownsValid()
{
var isValid = true;
$('select').map(function()
{
if($(this).val() == -1)
{
isValid = false;
}
});
return isValid;
}
Then wire into your submit button like so
<asp:Button ID="myButton" runat="server" OnClientClick="return isDropDownsValid" Text="Submit />
Here is a fiddle with a demo. You may need to change the selector $('select') to target the exact dropdowns you need.