Disable/remove value in dropdown menu after being selected - c#

Just wanna ask u guys for help. I have this dropdown menu in my abc.aspx page. There, user will choose month and enter the expenses and prices in the textbox provided. It will be saved in session :
session["month"]= dropdownlist1.selectedvalue;
session["expense1"] - textbox1.text;
session["price1"] - textbox2.text;
server.transfer ("sdf.aspx");
In the next page, the entered data will be viewed in label:
Label1.Text = session ["month"].ToString();
Label2.Text = session ["expense1"].ToString();
Label3.Text = session ["price1"].ToString();
Ok, my question is, how can make the month in drop down menu can be selected only once? Lets say, if the user choose Febuary, next time if he login, he cant choose the febuary anymore. I have used this code:
asp:DropDownList ID="DropDownList2" runat="server"
onchange="if(this.value!='Please choose') this.disabled='true';" Font-Bold="True">
<asp:ListItem>Please choose</asp:ListItem>
<asp:ListItem>January</asp:ListItem>
<asp:ListItem>Febuary</asp:ListItem>
<asp:ListItem>March</asp:ListItem>
But the problem is when i chose March, in the next page it supposed to show March isnt it? But, it shows 'Please choose'. So, i really hope there's someone here can help me out. Thank you.

Why not try the following:
ASPX
<asp:DropDownList ID="DropDownList1" runat="server" Font-Bold="True" AutoPostBack="true" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
<asp:ListItem Text="Please choose" Value=""></asp:ListItem>
<asp:ListItem Text="January" Value="January"></asp:ListItem>
<asp:ListItem Text="February" Value="February"></asp:ListItem>
<asp:ListItem Text="March" Value="March"></asp:ListItem>
</asp:DropDownList>
C#
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (Session["Month"] != null)
{
if (DropDownList1.SelectedValue == Session["Month"])
{
DropDownList1.SelectedValue = string.Empty;
}
else
{
Session["Month"] = DropDownList1.SelectedValue;
}
}
}
Make this is the ASPX and C# on your first page.

Related

My panel fails to show if the user clicks a specific drop down list item

I am attempting to get a <div> to appear when a specific ListItem is selected.
In my code behind I have:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (reportedBefore.SelectedItem.Text=="yes")
{
reportedBeforePanel.Visible = true;
}
else
{
reportedBeforePanel.Visible = false;
}
}
I referred to this article here initially, which stated I needed a few things:
You need to Enable the AutoPostBack of the dropdownlist for raising the OnSelectedIndexChanged event on server side.
AutoPostBack="true"
OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged
Admittedly, I did not have an AutoPostBack before. After adding it, I am afraid for some reason the requested div still does not show.
<asp:DropDownList ID="reportedBefore" CssClass="larger-drop-2" AutoPostBack="true" runat="server" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
<asp:ListItem Text="Select" Value="Select"></asp:ListItem>
<asp:ListItem Text="No" Value="No"></asp:ListItem>
<asp:ListItem Text="Yes" Value="Yes"></asp:ListItem>
<asp:ListItem Text="Unsure" Value="Unsure"></asp:ListItem>
</asp:DropDownList>
<asp:Panel ID="reportedBeforePanel" runat="server" Visible="false">
<div id="showDiv">
<label for="yesDetails">
Please provide details
</label>
<asp:TextBox ID="yesDetails" CssClass="third-w-form" runat="server"/>
</div>
</asp:Panel>
Would someone be so kind to help me out here?
The problem is in the following if-condition:
reportedBefore.SelectedItem.Text=="yes"
By this, you are doing a case-sensitive string comparison (this is the default in .NET), but the values in your dropdownlist are written in a different way ("Yes" vs. "yes").
In order to fix this, either perform a case-insensitive string comparison
string.Compare(reportedBefore.SelectedItem.Text, "yes", true) == 0
or change the casing in the if-statement.
C# is case sensitive, so it's "Yes" not "yes":
reportedBeforePanel.Visible = reportedBefore.SelectedItem.Text == "Yes";
Alternatievely you can use this:
reportedBeforePanel.Visible = reportedBefore.SelectedItem.Text.Equals("yes", StringComparison.InvariantCultureIgnoreCase);

Populating /Refreshing Drop down list based on user input

I am working on an asp.net application. I have a drop down list of customer account no. When i enter customer id card number in text box and click search button, the drop down should be populated with all the account numbers provided against that id card number previously. It works fine but when i add a new id card number and click search the drop down still retains the previous customer's account numbers. I want the drop down to empty and reppulate everytime i click Search and the item at value 1 i.e Other should stay constant rest of the list changes dynamically.
protected void Search_Click(object sender, EventArgs e)
{
ddl_accno.Items.Clear();
ddl_accno.Items.Add(new ListItem("Other", "0"));
string cnic = txt_cnic.Text;
BindControls.ControlBinder.BindDropDown(ddl_accno, UL.GetAccountNo(cnic),"ACCOUNT_NO","ACCOUNT_NO");
}
<td style="width:275px">
<label for="textfield">
Account no.</label>
<asp:DropDownList Font-Size="Small" ID="ddl_accno"
runat="server" AutoPostBack = "True"
Width="319px" AppendDataBoundItems="true"
onselectedindexchanged="ddl_accno_SelectedIndexChanged">
<asp:ListItem Value="0" Selected="True" Text="Select Account No"></asp:ListItem>
<asp:ListItem Value="1" Text="Other"></asp:ListItem>
</asp:DropDownList><br />
I am using UL.GetAccountNO() function to populate ddl with query. If the user selects other a text box will be visible where user can enter an account number apart from the ones in the drop down.
Pasting a sample code:
Design:
<asp:DropDownList ID="AssignedToDropDownList" runat="server" DataSourceID="UserLinqDataSource"
DataTextField="UserName" DataValueField="UserId" AppendDataBoundItems="true"
SelectedValue='<%# Bind("AssignedTo") %>'>
</asp:DropDownList>
Code Behind:
protected void Page_Load(object sender, EventArgs e)
{
DDLDataBind();
}
private void DDLDataBind()
{
AssignedToDropDownList.Items.Clear();
AssignedToDropDownList.Items.Add(new ListItem("--did not assign--", "0"));
AssignedToDropDownList.DataBind();
}

Dropdown list value not displaying

hi i have gridview that when a row is selected, it populates into textboxes that are used to populate the gridview itself. the last field is a dropdownlist and its not displaying when the gridview is clicked. i set a breakpoint and see that its stuck on the first - 0 index. i dont know why it isnt moving forward... here is the code:
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
....
if (DropDownListCurrency.Items.FindByValue(row.Cells[7].Text.ToString().Trim) != null)
{
DropDownListCurrency.SelectedValue = row.Cells[7].Text.ToString().Trim();
}
....
}
<asp:DropDownList ID="DropDownListCurrency" runat="server"
CausesValidation="True"
DataSourceID="CurrencyDropDownListDataSource"
DataTextField="Currency" DataValueField="Currency_ID"
AppendDataBoundItems="True">
<asp:ListItem Value="0" Text="<Select>" Enabled="True" Selected="False"></asp:ListItem>
</asp:DropDownList>
why you want take the value from textbox. Will better use DataKeyNames like this inside that event
GridViewRow row = GridView.SelectedRow;
int id = Convert.ToInt32(GridView.DataKeys[row.RowIndex].Value);
this work if you have only one value in DataKeyName if you look not there a index if you want have more than one value use this
int id = Convert.ToInt32(GridView.DataKeys[row.RowIndex].Values["FirstValue"]);
string name = Convert.ToString(GridView.DataKeys[row.RowIndex].Values["SecondValue"]);
Does the DropDownList contains the words that you wanna show displayed?
You need to set the AutoPostBack property to True:
it should be :
<asp:DropDownList ID="DropDownListCurrency" AutoPostBack="True" runat="server"
CausesValidation="True"
DataSourceID="CurrencyDropDownListDataSource"
DataTextField="Currency" DataValueField="Currency_ID"
AppendDataBoundItems="True">
<asp:ListItem Value="0" Text="<Select>" Enabled="True" Selected="False"></asp:ListItem>
</asp:DropDownList>
made a simple error...
called the wrong field was supposed to be value (Currency_ID) and not the text (Currency)
DropDownListCurrency.SelectedValue = GridView1.DataKeys[row.RowIndex].Values["Currency_ID"].ToString().Trim();

DropDownList doesn't change it's value when Navigate to other page

I have a Dropdownlist in my aspx page, with value:
//DropDownlist value: 1--> show notice in one day ago; 2--> 7 days ago;3--> 30 days ago.
<asp:DropDownList ID="DropDownListTime" runat="server">
AutoPostBack="true" >
<asp:ListItem Selected="True"></asp:ListItem>
<asp:ListItem Value="1"> 1 day ago </asp:ListItem>
<asp:ListItem Value="2"> 7 days ago </asp:ListItem>
<asp:ListItem Value="3"> 30 days ago </asp:ListItem>
</asp:DropDownList>
And code in cs page:
protected void Page_Load(object sender, EventArgs e)
{ if (!IsPostBack)
{
BindData();
}
}
public void BindData()
{
string key="";
if (string.IsNullOrEmpty(DropDownListTime.SelectedValue))
{
key = "3";
}
else
{
key = DropDownListTime.SelectedValue.ToString();
}
HyperLink1.NavigateUrl = string.Format("Allnotice.aspx?key={0}",key);
// go to page to show all notices with `1 day`,`7days`,`30 days` ago depend on the `key`
}
public void IndexNotice_Changed(Object sender, EventArgs e)
{
BindData();
}
When debugging, the key is right with the option I choose. But After choose an option in Dropdownlist, I click in the Hyperlink, it pass to Allnotice.aspx page with key="3". Always and always even what option I chose.
For detail: I choose 7 days ago---> debug: key= 2--> then click on Hyperlink---> the next page recieved the key=3.
Help!!!!
UPDATE: I've asked this problem but no one can help. So I try to describe it in a simple way, hope you dont mind if it's duplicate.
DropDownList doesn't change it's value
You have not assigned an event handler to DropdownList control, so even though page is posting back it won't fire IndexNotice_Changed event as you are expecting.
//Assign IndexNotice_Changed event to the OnSelectedIndexChanged
<asp:DropDownList ID="DropDownListTime"
Runat="server" AutoPostBack="true"
OnSelectedIndexChanged="IndexNotice_Changed" > //NOTE HERE
<asp:ListItem Selected="True"></asp:ListItem>
<asp:ListItem Value="1"> 1 day ago </asp:ListItem>
<asp:ListItem Value="2"> 7 days ago </asp:ListItem>
<asp:ListItem Value="3"> 30 days ago </asp:ListItem>
</asp:DropDownList>
<asp:HyperLink ID="HyperLink1" runat="server"></asp:HyperLink>
one option could be using a hiddenfield value in javascript to save always the selected option
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js' type='text/javascript'></script>
<script type="text/javascript">
$("#<%=DropDownListTime.ClientID%>").change(function(e) {
var dpdVal=$("#<%=DropDownListTime.ClientID%>").val();
document.getElementById("<%=hiddenFieldControl.ClientID%>").value=dpdVal;
});
</script>
so, you can replace for this:
public void BindData()
{
string key="";
if (string.IsNullOrEmpty(hiddenFieldControl.Value))
{
key = "3";
}
else
{
key = hiddenFieldControl.Value.ToString();
}
HyperLink1.NavigateUrl = string.Format("Allnotice.aspx?key={0}",key);
// go to page to show all notices with `1 day`,`7days`,`30 days` ago depend on the `key`
}

The RequiredFieldValidator for a drop down control inside of user control does not fire

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"

Categories