Using C# I need the value in the Hiddenfield below, which is currently "test" to be the 'Text' of the DropDownList. Any Ideas?
HiddenField hiddenField = new HiddenField { ID = "ValueHiddenField", Value = "test" };
.cs page.
protected void Page_Load(object sender, EventArgs e)
{
HiddenField hiddenField = new HiddenField { ID = "ValueHiddenField", Value = "test" };
theForm.Controls.Add(hiddenField);
string script = #"function updateCallBackReason() {
callBackReason = document.getElementById('<%=ValueHiddenField.ClientID %>').value;
return callBackReason;
}";
this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "callBackReasonScript", script, true);
.aspx
<asp:label runat="server" ID="lblCallbackReason" AssociatedControlID="dropCallbackReason" CssClass="textLabel">Reason for callback:</asp:label>
<asp:DropDownList runat="server" ID="dropCallbackReason" onChange="updateCallBackReason" ClientIDMode="Static" >
<asp:ListItem Text="-- Select Reason --" Value="1"></asp:ListItem>
<asp:ListItem Text="Booking a Test Drive" Value="6"></asp:ListItem>
<asp:ListItem Text="Discussing a Purchase" Value="11"></asp:ListItem>
<asp:ListItem Text="Contract Hire Quotation" Value="45"></asp:ListItem>
</asp:DropDownList>
After binding your drop down to a data source, set the selected value of the drop down to the index of the text in the hidden field.
dropCallbackReason.SelectedIndex = dropCallbackReason.Items.IndexOf(dropCallbackReason.Items.FindByText(ValueHiddenField.Value.ToString()));
I'd say your function updateCallBackReason is not doing what is supposed to do (update hidden field value). If didn't get wrong your question, this is what you have to do.
string script = string.Format(#"function updateCallBackReason() {{
var ddl = document.getElementById('dropCallbackReason');
var callBackReason = document.getElementById('{0}');
callBackReason.value = ddl.options[ddl.selectedIndex].innerHTML;
}}", hiddenField.ClientID );
Related
I am trying to stop the user to enter a numerical value in the search criteria text box when the Dropdown value is MBID The code works I only need help on how to resolve the validation issue
C# Code
protected bool searchData()
{
string val = DropDownList1.SelectedItem.Value;
switch (val)
{
case "MBID":
using (SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["Molecular"].ConnectionString))
{
con.Open();
using (SqlCommand cmd = new SqlCommand(#"SELECT count(*)
from Patient where MBID = #SearchCriteria ", con))
{
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
int userCount = (Int32)cmd.ExecuteScalar();
da.Fill(dt);
}
}
}
}
The Search button call the code below
protected void btnSearch_Click(object sender, EventArgs e)
{
if (FormValidation()) if (searchData())
{
BindGrid();
inputUpdateFornData();
}
}
HTML Code
<asp:DropDownList ID="DropDownList1" runat="server" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
<asp:ListItem Value="MBID">MBID</asp:ListItem>
<asp:ListItem Value="HPNumber">HP Number</asp:ListItem>
<asp:ListItem Value="NHSNumber">NHS Number</asp:ListItem>
I cannot used the code below because numerical value can be entered for the other option of the dropdown
<asp:TextBox ID="txtSearchCriteria" runat="server />
<asp:CompareValidator ID="cv" runat="server" ControlToValidate="txtSearchCriteria" Type="Integer"
Operator="DataTypeCheck" ErrorMessage="Value must be an integer!" />
This is how to do it:
try
{
int d = int.Parse(txtSearchCriteria.Text);
//if works str is a number
}
catch (Exception e)
{
Console.WriteLine("It isn't a number!");
}
Add ClientValidationFunction="validateFunction" in your CompareValidator.
And write validation function as follows-
function validateFunction(s,args){
if (yourdropdown.value == "MBID")
{
// Your code
}
}
If you want server validation , add OnServerValidate attribute and handler function on server side.
hello please try below code for javascript validation
below is javascript code
<script>
function validateSearch()
{
var dropdown = document.getElementById("<%= ddlSearch.ClientID %>");
var txtSearch = document.getElementById("<%= txtSearch.ClientID %>");
if (dropdown.value == "MBID")
{
var reg = /^\d+$/;
if (!reg.test(txtSearch.value)) {
alert("Please enter proper value");
txtSearch.focus();
return false;
}
}
}
</script>
and below is aspx code of dropdown and textbox.
<asp:DropDownList runat="server" ID="ddlSearch">
<asp:ListItem Text="Select" Value="-1"></asp:ListItem>
<asp:ListItem Text="MBID" Value="MBID"></asp:ListItem>
<asp:ListItem Text="Name" Value="Name"></asp:ListItem>
</asp:DropDownList>
<asp:TextBox runat="server" ID="txtSearch"></asp:TextBox>
<asp:Button runat="server" ID="btnSearch" Text="Search" OnClientClick="return validateSearch();" />
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 need to declare the 'text value' of the dropdownlist 'dropCallbackReason' into the 'ValueHiddenField' ID of the so that I can then use it as a javascript variable.
I need to be able to declare the HiddenField through C# as aswell as declaring the Javascript Variable 'callBackReason' through c# as well, any ideas how to do this through C#?
.cs page.
protected void Page_Load(object sender, EventArgs e)
{
HiddenField hiddenField = new HiddenField { ID = "ValueHiddenField", Value = "test" };
theForm.Controls.Add(hiddenField);
string script = #"function updateCallBackReason() {
callBackReason = document.getElementById('<%=ValueHiddenField.ClientID %>').value;
return callBackReason;
}";
this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "callBackReasonScript", script, true);
.aspx
<asp:label runat="server" ID="lblCallbackReason" AssociatedControlID="dropCallbackReason" CssClass="textLabel">Reason for callback:</asp:label>
<asp:DropDownList runat="server" ID="dropCallbackReason" onChange="updateCallBackReason" ClientIDMode="Static" >
<asp:ListItem Text="-- Select Reason --" Value="1"></asp:ListItem>
<asp:ListItem Text="Booking a Test Drive" Value="6"></asp:ListItem>
<asp:ListItem Text="Discussing a Purchase" Value="11"></asp:ListItem>
<asp:ListItem Text="Contract Hire Quotation" Value="45"></asp:ListItem>
</asp:DropDownList>
Here is how to add a HiddenField control programmatically. Note that controls cannot be added into Page.Controls directly - they should be placed into some container, like ContentPlaceholder or Panel:
HiddenField hiddenField = new HiddenField {ID = "ValueHiddenField", Value = "test"};
SomePanel.Controls.Add(hiddenField);
And here is how to register a script block:
string script = #"function updateCallBackReason() {
callBackReason = document.getElementById('<%=ValueHiddenField.ClientID %>').value;
return callBackReason;
}";
this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "callBackReasonScript", script, true);
Good places to do this are either Page_Load or Page_PreRender.
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();