I have a DropDownList that is populated from a datasource. After it is bound, I place an empty field at the top of the list so that it appears blank to the user (creating a sort of 'default item'). I have some code behind handling the SelectedIndexChanged event, but it doesn't really need to be executed if the user were to select the empty ListItem.
Here is my code:
.aspx
<asp:DropDownList ID="dropDownList" runat="server" AutoPostBack="true" OnSelectedIndexChanged="dropDownList_SelectedIndexChanged">
</asp:DropDownList>
C# Codebehind adding the blank ListItem
dropDownList.Items.Insert(0, new ListItem(String.Empty, String.Empty));
dropDownList.SelectedIndex = 0;
Since I don't need the page to do a postback when the user clicks just this specific index, I want to disable postback entirely for just this listitem. Is this even possible? If so, how?
Set disabled="disabled", this will make the item not selectable (and not do postback)
<asp:DropDownList runat="server" ID="dddl">
<asp:ListItem Text="" disabled="disabled" Selected="True"></asp:ListItem>
<asp:ListItem Text="test"></asp:ListItem>
</asp:DropDownList>
Alternatively if you want to be able to select the first (empty) item but not do postback, do this:
<asp:DropDownList runat="server" ID="dddl" AutoPostBack="true" onchange="if(this.selectedIndex == 0)return false;">
<asp:ListItem Text="" Selected="True"></asp:ListItem>
<asp:ListItem Text="test"></asp:ListItem>
</asp:DropDownList>
You could add a required field validator. Then set the CausesValidation property of the DropDownList to true. This will prevent the postback and also provide the end-user feedback.
<asp:DropDownList ID="dropDownList" runat="server" AutoPostBack="true" OnSelectedIndexChanged="dropDownList_SelectedIndexChanged" CausesValidation="true">
</asp:DropDownList>
<asp:RequiredFieldValidator ID="rfvDropDownList" runat="server" ErrorMessage="Must select a value!" ControlToValidate="dropDownList" />
Could you add an onChange attribute to run a JS function that checks if the value is empty before posting back?
i.e.
dropDownList.Attributes.Add("onChange", "javascript: return ddlChange()");
function ddlChange
{
if(document.getElementById("<%= dropDownList.ClientID %>").value == "")
return false;
return true;
}
1.web control use postback, add attribute to cancel postback.
but option will not be selected.
protected void rblRecentOrder_DataBound(object sender, EventArgs e)
{
RadioButtonList rbl = sender as RadioButtonList;
ListItem itemX = rbl.Items.FindByText("NA");
// if no NA item then add it
if (itemX == null)
{
itemX = new ListItem("NA");
// set item cancel postback, but option will not be selected
itemX.Attributes.Add("onclick", "return false;");
}
}
2.or use javacsript call postback when need
<script>
function myPostback() {
// call asp.net postback
__doPostBack('tagName', 'params');
}
// TextBox
function updateValue(id, value) {
let obj = document.getElementById(id);
obj.value = value;
}
// Label
function updateInnerHTML(id, value) {
var obj = document.getElementById(id);
obj.innerHTML = value;
}
// DrowdownList
function setSelectOption(id, value) {
let obj = document.getElementById(id);
if (obj)
obj.value = value;
}
// RadioButtonList
function selectRadio(id) {
let obj = document.getElementById(id);
// input type=radio
if (obj) {
let items = obj.getElementsByTagName("INPUT");
for (var i = 0; i < items.length; i++) {
items[i].checked = true;
}
}
}
</script>
c#
switch(Request.Form["__EVENTTARGET"])
{
case "tageName":
var params = Request.Form["__EVENTARGUMENT"];
//..........
break;
}
Related
I have a Radiobuttonlist. In items i was adding Specify your own value with One textbox. I f i clicked on that text-box radio-button should select b y default.
<td style="text-align:left" class="contract_value_bg" width="50%">
<asp:RadioButtonList ID="rblDocumentstType" runat="server" AutoPostBack="true" OnSelectedIndexChanged="rblDocumentstType_SelectedIndexChanged" RepeatColumns="1">
</asp:RadioButtonList>
<asp:TextBox ID="txtRFP" runat="server" AutoPostBack="true" OnTextChanged="txtRFP_TextChanged" MaxLength="120" />
</td>
enter image description here
You want to set focus on the textbox if "specify your own value" was clicked in the RadioButtonList? Or you want to select that item in the RadioButtonList if the user clicked into the TextBox?
This is for the former case:
protected void rblDocumentstType_SelectedIndexChanged(Object sender, EventArgs e)
{
RadioButtonList rblDocumentstType = (RadioButtonList) sender;
if(rblDocumentstType.SelectedIndex == 1)
{
txtRFP.Focus();
}
}
If you want to select the second RadioButtonList item if the TextBox got focus you should do that at client-side by handling the onfocus event with javascript (or jQuery):
<asp:TextBox ID="txtRFP" runat="server" onfocus="selectSpecifyYourOwn()" AutoPostBack="true" OnTextChanged="txtRFP_TextChanged" MaxLength="120" />
function selectSpecifyYourOwn() {
var rbID = '<%=rblDocumentstType.ClientID %>';
var rb = document.getElementById(rbID);
var items = rb.getElementsByTagName("input");
items[1].checked = true;
}
I have a page with a gridview on it and a dropdown list which controls how many items per page the gridview will display.
The pageSize value of the gridview is controlled by this dropdown list and it gets saved to a cookie.
When the user loads the site the cookie is read so that it remembers what page size the user picked.
I have one problem and that is, if I pick another value on the dropdown list it does not update either cookie or dropdown list. It reverts back to the saved value.
This is the dropdown list created in the gridview pager template:
<PagerTemplate>
<asp:Table ID="Table3" runat="server" Width="100%">
<asp:TableRow>
<asp:TableCell HorizontalAlign="Left">
<asp:PlaceHolder ID="ph" runat="server"></asp:PlaceHolder>
</asp:TableCell>
<asp:TableCell HorizontalAlign="Right" Width="10%">
Page Size
<asp:DropDownList runat="server" ID="ddlPageSize" AutoPostBack="true"
OnSelectedIndexChanged="ddlPageSize_SelectedIndexChanged" OnLoad="ddlPageSize_Load">
<asp:ListItem>5</asp:ListItem>
<asp:ListItem>10</asp:ListItem>
<asp:ListItem>20</asp:ListItem>
<asp:ListItem>50</asp:ListItem>
<asp:ListItem>100</asp:ListItem>
</asp:DropDownList>
</asp:TableCell>
</asp:TableRow>
</asp:Table>
</PagerTemplate>
and this is where I try to load the value of the dropdown list from cookie:
protected void Page_Load(object sender, EventArgs e)
{
string pageSize = "10";
//Try and load the PageSize cookie from the user's machine and default to 10 records if none is found.
if (Request.Cookies["PageSize"] != null)
{
if (Request.Cookies["PageSize"]["Value"] != null)
{
pageSize = Request.Cookies["PageSize"]["Value"];
int _pageSize;
int.TryParse(pageSize, out _pageSize);
gvRecordsList.PageSize = _pageSize;
DropDownList ddlPageSize = (gvRecordsList.BottomPagerRow).FindControl("ddlPageSize") as DropDownList;
ddlPageSize.SelectedIndex = ddlPageSize.Items.IndexOf(new ListItem(pageSize));
}
}
else
gvRecordsList.PageSize = 10;
if (IsPostBack)
{
ApplyPaging();
}
else
{
gvRecordsList.DataSourceID = "RecordsListSqlDataSource";
gvRecordsList.DataBind();
}
}
The dropdown list index changed code:
protected void ddlPageSize_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddlPageSize = (gvRecordsList.BottomPagerRow).FindControl("ddlPageSize") as DropDownList;
gvRecordsList.PageSize = int.Parse(ddlPageSize.SelectedValue);
Response.Cookies["PageSize"]["Value"] = ddlPageSize.SelectedValue;
Response.Cookies["PageSize"].Expires = DateTime.Now.AddDays(1d);
}
When I step through the code of the SelectedIndexChanged method, I can see that ddlPageSize.SelectedValue always contains the value from the cookie, 50, even though I select another value.
I guess the question is, where do I set the index of the dropdown list?
DropDownList ddlPageSize = (gvRecordsList.BottomPagerRow).FindControl("ddlPageSize") as DropDownList;
ddlPageSize.SelectedIndex = ddlPageSize.Items.IndexOf(new ListItem(pageSize));
The Page_Load event executes before the DropDownList SelectedIndexChanged event. And you are loading the cookie's value to the DropDownList on the PageLoad event.
I suggest you to try loading the cookie afterwards, on the OnPreRender event for example.
Or add a condition to your Page_Load logic, verifying if the PostBack is caused by the DropDownList:
DropDownList ddlPageSize = (gvRecordsList.BottomPagerRow).FindControl("ddlPageSize") as DropDownList;
bool isDDLPostingBack = Request["__EVENTTARGET"] == ddlPageSize.UniqueID;
if (Request.Cookies["PageSize"]["Value"] != null && !isDDLPostingBack)
{
...
}
I have an edit button and a dropdownlist inside a formview. I am using Linq To Entities to get the data I need to work with and have no problem populating and viewing the formview itemtemplate.
However, the dropdownlist control (id="ddlEligibility") is only in theedititemtemplate (I use a textbox in the itemtemplate to display the current value) and I am having a problem getting the value initially shown in the itemtemplate to appear when the edititemtemplate is shown. All I get right now is the dropdownlist with the first value shown. I want the value from the itemtemplate to appear by default and the user can change it if they wish. Here is the code that populates the dropdownlist. Anyone have a suggestions?
protected void btnEdit_Click(object sender, EventArgs e)
{
fvSubscriber.ChangeMode(FormViewMode.Edit);
fvSubscriber.DataBind();
LifeLineDSEntities context = new LifeLineDSEntities():
var program = from p in context.EligibilityPrograms
select p;
DropDownList ddlEligibility = (DropDownList)(fvSubscriber.FindControl("ddlEligibility")));
if (ddlEligibility != null)
{
ddlEligibility.DataSource = program;
ddlEligibility.DataTextField = "ProgramName";
ddlEligibility.DataValueField = "eligibilityCode";
ddlEligibility.DataBind();
}
}
DropDownlist in FormView...
<form id="form1" runat="server">
<asp:FormView ID="fvSubscriber" runat="server" RenderOuterTable="false" DefaultMode="Readonly" OnModeChanging="fvSubscriberChanging">
<ItemTemplate>
<asp:TextBox ID="txtEligibility" runat="server" Text='<%# Eval("ProgramName") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddlEligibility" runat="server" />
</EditItemTemplate>
</asp:FormView>
</form>
You could try getting the value of the textbox before you change the formview mode.
TextBox txtEligibility= (TextBox)fvSubscriber.FindControl("txtEligibility");
fvSubscriber.ChangeMode(FormViewMode.Edit);
fvSubscriber.DataBind();
LifeLineDSEntities context = new LifeLineDSEntities():
var program = from p in context.EligibilityPrograms
select p;
DropDownList ddlEligibility = (DropDownList)(fvSubscriber.FindControl("ddlEligibility")));
if (ddlEligibility != null)
{
ddlEligibility.DataSource = program;
ddlEligibility.DataTextField = "ProgramName";
ddlEligibility.DataValueField = "eligibilityCode";
ddlEligibility.DataBind();
if (txtEligibility != null)
{
if(!string.IsNullOrWhiteSpace(txtEligibility.Text))
{
foreach (ListItem item in ddlEligibility.Items)
{
if (item.Text == txtEligibility.Text)
{
ddlEligibility.SelectedValue = txtEligibility.Text;
}
}
}
}
}
Following is the test scenario for my code.
1) Once the user selects one of the radio buttons on Webpage.aspx, a modal popup extender shows up.
2) A user control (SSL_Ticket.ascx) is defined inside the modal popup window.
3) A RequiredFieldValidator is defined for a drop down list contained inside the user control.
4) If the user selects the "0" value from drop down list, no validation error message is displayed.
Code
Webpage.aspx
<asp:RadioButtonList ID="RadioButtonListForTicket" runat="server" AutoPostBack="true"
OnSelectedIndexChanged="radioButtonListForTicket_OnSelectedIndexChanged">
<asp:ListItem Selected="True">No</asp:ListItem>
<asp:ListItem>Yes</asp:ListItem>
</asp:RadioButtonList>
<ajaxToolkit:ModalPopupExtender ID="ModalPopupExtenderForTicket" runat="server" BackgroundCssClass="popUpStyle"
DropShadow="true" PopupControlID="divTicketPreview" PopupDragHandleControlID="panelDragHandle"
TargetControlID="btnForPopupAppear" CancelControlID="btnForPopupDisappear"/>
....
...
Webpage.aspx.cs
protected void radioButtonListForTicket_OnSelectedIndexChanged(object sender, System.EventArgs e)
{
if (RadioButtonListForTicket.SelectedItem.Text.ToString().Equals("Yes"))
{
// Check if the sites are selected
updateSelectionCount();
updateListOfSites();
if (selectionCount == 0)
{
lblSSLTicketSelection.Text = "Please select a site.";
RadioButtonListForTicket.SelectedValue = "No";
return;
}
else
{
lblSSLTicketSelection.Text = "";
}
....
ModalPopupExtenderForTicket.Show();
}
}
...
SSL_Ticket.ascx
<asp:DropDownList ID="cmbRootCause" runat="server" Width="255px" OnSelectedIndexChanged="cmbRootCause_SelectedIndexChanged" AutoPostBack="true"
CausesValidation="true">
<asp:ListItem Value="0">Select</asp:ListItem>
<asp:ListItem Value="1">Item1</asp:ListItem>
</asp:DropDownList>
<asp:RequiredFieldValidator ID="reqdFieldForRootCause" runat="server" ControlToValidate="cmbRootCause" InitialValue="Select"
ErrorMessage="Please select root cause" ValidationGroup="validateRootCause" Visible="false" Display="Dynamic" EnableClientScript="true">
</asp:RequiredFieldValidator>
...
SSL_Ticket.ascx.cs
protected void cmbRootCause_SelectedIndexChanged(object sender, EventArgs e)
{
if (cmbRootCause.SelectedItem.ToString().Equals("Other"))
{
lblcmbRootCause.Text = "";
lblcmbRootCause.Visible = false;
txtRootCauseOther.Visible = true;
}
else if (cmbRootCause.SelectedItem.ToString().Equals("Select"))
{
lblcmbRootCause.Visible = true;
lblcmbRootCause.Text = "Please select root cause";
}
else
{
lblcmbRootCause.Text = "";
lblcmbRootCause.Visible = false;
txtRootCauseOther.Visible = false;
}
}
I did browse through couple of solutions (ValidateProperty, Client-side validation, RangeValidation, etc), but it did not fire validation text.
This did not help - Handling RequiredFieldValidator inside of a User Control
I'd appreciate your help very much.
Thanks!!!
Remove visible = false attribute from required field validator, by default they won't show up in the beginning.
<asp:RequiredFieldValidator ID="reqdFieldForRootCause" runat="server" ControlToValidate="cmbRootCause" InitialValue="Select"
ErrorMessage="Please select root cause" ValidationGroup="validateRootCause" **Visible="false"** Display="Dynamic" EnableClientScript="true">
</asp:RequiredFieldValidator>
Well in your 'RequiredFieldValidator' for your DropDownList you need to remove this:
InitialValue="Select"
I'm basically trying to bind the dropdown list with the radio buttons. there are 4 options in the dropdown menu according to which the radio buttons should be selected.
with the first two options, the radio buttons should be active and with the rest of two objects in the dropdown menu, the radio buttons should become inactive.
here is my front end code for dropdown:
<asp:DropDownList ID="ddLType" runat="server" Width="406px" Height="23px">
<asp:ListItem Value="Prof">Professional</asp:ListItem>
<asp:ListItem>Enterprise</asp:ListItem>
<asp:ListItem>Maintanence</asp:ListItem>
<asp:ListItem>Reporting</asp:ListItem>
</asp:DropDownList>
here is my code for radio buttons:
<asp:RadioButtonList ID="rdoMeapSupport" RepeatDirection="Horizontal" runat="server" AutoPostBack="True" >
<asp:ListItem Value="1" Text="Yes" />
<asp:ListItem Value="0" Text="No" />
</asp:RadioButtonList>
if we select professional, the radio buttons should be active with yes as the checked option.
with enterprise, both the buttons should be active but not selected.
with maintenance and reporting, the buttons should become inactive.
First of all you have to set the property of drop down list called AutoPostBack to true. You can do this by simply selecting your drop down list and set AutoPostBack = true from properties window.
Then go to code behind file write these codes:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
if (ddLType.SelectedValue == "Professional")
{
rdoMeapSupport.Enabled = true;
rdoMeapSupport.SelectedValue = "Yes";
}
}
}
after that set event for your radio button list "SelectedIndexChanged"
and paste this code inside that
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddLType.SelectedValue == "Professional")
{
rdoMeapSupport.Enabled = true;
rdoMeapSupport.SelectedValue = "Yes";
}
if (ddLType.SelectedValue == "Enterprise")
{
rdoMeapSupport.SelectedValue = null;
rdoMeapSupport.Enabled = true;
}
if ((ddLType.SelectedValue == "Maintanence") || (ddLType.SelectedValue == "Reporting"))
{
rdoMeapSupport.SelectedValue = null;
rdoMeapSupport.Enabled = false;
}
}
Apply AutoPostBack="true" attribute to the dropdown and do the below logic in the selected index change event.
<asp:DropDownList ID="ddLType" runat="server" Width="406px" Height="23px"
onselectedindexchanged="ddLType_SelectedIndexChanged" AutoPostBack="true" >
<asp:ListItem Value="Prof">Professional</asp:ListItem>
<asp:ListItem>Enterprise</asp:ListItem>
<asp:ListItem>Maintanence</asp:ListItem>
<asp:ListItem>Reporting</asp:ListItem>
</asp:DropDownList>
<asp:RadioButtonList ID="rdoMeapSupport" RepeatDirection="Horizontal" runat="server"
AutoPostBack="True">
<asp:ListItem Value="1" Text="Yes" />
<asp:ListItem Value="0" Text="No" />
</asp:RadioButtonList>
protected void ddLType_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddLType.SelectedIndex == 0 || ddLType.SelectedIndex == 1)
{
rdoMeapSupport.Enabled = true;
}
else
{ rdoMeapSupport.Enabled = false; }
}
I think making radio buttons active, but not allowing to select is none of use, better you disable it.
You may use jquery for this:
<script>
$(function () {
$("# <%# ddLType.ClientID %>").change(function () {
var selVal = $(this).val();
if(selVal == "Prof"){
$('#rb_Statusno').removeAttr('disabled');
else
$('#rb_Statusno').attr('disabled', true);
}
</script>
For more help you may go through this post.