Enabling & Disabling Drop Down Lists - c#

I have a web form with two drop down lists.
The 1st drop down list contains 2 values &
the 2nd drop down list contains 3 values.
My objective is, when I select the 1st value of the 1st drop down list, the 2nd dropdownlist should not be visible, but when i select the 2nd value of the 1st dropdownlist, the 2nd dropdownlist should appear.

You need to set the AutoPostBack-property of your first drop down list to true and add an OnSelectedIndexChanged-EventHandler
<asp:DropDown id="FirstList" runat="server" AutoPostBack="true" OnSelectedIndexChanged="FirstList_Changed"></asp:DropDown>
In your EventHandler you can check the selected index and act accordingly.
protected void FirstList_Changed(object sender, EventArgs e) {
if(FirstList.SelectedIndex == 0) {
SecondList.Visible = false;
} else {
SecondList.Visible = true;
}
}
However you can also do the same thing with JavaScript (see BPX's solution).

If you want to enable and disable you can use this Code
<asp:DropDownList ID="ddl1" runat="server" AppendDataBoundItems="true" AutoPostBack="true" Width="100%">
<asp:ListItem Text="" ></asp:ListItem>
<asp:ListItem Text="Value 1" Value="1"></asp:ListItem>
<asp:ListItem Text="Value 2" Value="2"></asp:ListItem>
</asp:DropDownList>
You need to set AutoPostBack="true" and in the SelectedIndexChanged write this code
protected void ddl1_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
if (ddl1.SelectedValue == "1")
{
ddl2.Enabled = false;
//ddl2.Visible = false;
}
else
{
ddl2.Enabled = true;
//ddl2.Visible = true;
}
}
catch (Exception ex)
{
string b= ex.Message;
}
}
For VISIBLE *enabling/disabling* USE the commented line and comment the other line
Hope this helps
Happy coding

You can do it by using JQuery. A sample code is given below.
$("#DropDownList1").change(function(){
indx = $("#DropDownList1 option:selected").index();
if(indx==1)
{
$("#DropDownList2").hide();
}
else
{
$("#DropDownList2").show();
}
})
Don't forget to add jquery plugin.

Related

C#: How do I check the value of a field before Wizard's next step? (NextButtonClick)

When the user clicks to "Continue" after the Wizard's first step I would like check that the value (selected index) of MyRadioBtn is 1. If not, then open a panel and do not proceed to Step 2 of the wizard.
The problem I'm having is the "MyRadioBtn.SelectedIndex" conditional never returns a value of 1.
Front-end:
<asp:RadioButtonList ID="MyRadioBtn" runat="server" AutoPostBack="True">
<asp:ListItem Value="0">No</asp:ListItem>
<asp:ListItem Value="1">Yes</asp:ListItem>
</asp:RadioButtonList>
Code-behind:
protected void Wizard1_NextButtonClick(object sender, WizardNavigationEventArgs e)
{
if (Wizard1.ActiveStepIndex == 0)
{
if (MyRadioBtn.SelectedIndex == 1)
{
//Stop the user from moving on to step 2
e.Cancel = true;
//Show the user a panel
WarningPanel.Visible = true;
}
else {
//Continue to STEP 2
}
}
}
Do you need to fire a postbkack after the user selects an item from de DropDownList? If not, change AutoPostBack="True" to AutoPostBack="False"

Update a label when I change a dropdown selection?

Basically I want my label priceLabel to automatically update when the user changes their selection on a dropdown list sizeDropdown
For example, they select a size from sizeDropdown, this then changes an amount decimal and then converts this decimal into a string and puts it into priceLabel. If the user changes there selection on sizeDropdown it automatically reupdates priceLabel.
This is what I currently have but it doesnt work:
In the HTML
<asp:DropDownList ID="sizeDropdown" runat="server" OnSelectedIndexChanged="sizeDropdown_SelectedIndexChanged"></asp:DropDownList>
Then in the aspx.cs
Values get Added in one method:
sizeDropdown.Items.Add("50g");
sizeDropdown.Items.Add("100g");
The in another I try to assign the price:
protected void sizeDropdown_SelectedIndexChanged(object sender, EventArgs e)
{
double amount = 0;
if (sizeDropdown.SelectedItem.Equals("50g"))
{
amount = 4.99;
}
else if (sizeDropdown.SelectedItem.Equals("100g"))
{
amount = 7.99;
}
priceLabel.Text = amount.ToString();
}
Thanks
EDIT: hank you everyone for the help! I will leave this ehre, and if anyones nterested in ow I fixed it just converted the selected value to a string then used that which saved a lot of hastle. Cheers!
You need to do two things
Add AutoPostBack="True" in tag to perform postback which is false by default.
Bind code in !Page.IsPostBack, so that your dropdown do not bind again and loose the selected option.
HTML
<asp:DropDownList ID="sizeDropdown" runat="server" AutoPostBack="True" OnSelectedIndexChanged="sizeDropdown_SelectedIndexChanged"></asp:DropDownList>
Code bhind
if( !Page.IsPostBack)
{
sizeDropdown.Items.Add("50g");
sizeDropdown.Items.Add("100g");
}
Use this in sizeDropdown Tag
AutoPostBack="True"
SelectedItem.Text in all conditions
if (sizeDropdown.SelectedItem.Text.Equals("50g"))
{
amount = 4.99;
}
if you adding the items in page_load event otherwise it is not needed
if(!Page.IsPostBack)
{
sizeDropdown.Items.Add("50g");
sizeDropdown.Items.Add("100g");
}
Aspx Code:
<asp:DropDownList ID="sizeDropdown" runat="server" AutoPostBack="True"
onselectedindexchanged="sizeDropdown_SelectedIndexChanged">
<asp:ListItem>Select</asp:ListItem>
<asp:ListItem Value="4.99">50gms</asp:ListItem>
<asp:ListItem Value="7.99">100g</asp:ListItem>
</asp:DropDownList>
<asp:Label ID="priceLabel" runat="server" Text="Label"></asp:Label>
.Cs Code
protected void sizeDropdown_SelectedIndexChanged(object sender, EventArgs e)
{
if (sizeDropdown.SelectedItem.Text != "Select")
{
priceLabel.Text = sizeDropdown.SelectedItem.Value;
}
else
{
priceLabel.Text = "";
}
}
Quick Solution
Please replace your code with following code.
aspx page :
<asp:DropDownList ID="sizeDropdown" runat="server" OnSelectedIndexChanged="sizeDropdown_SelectedIndexChanged" AutoPostBack="True"></asp:DropDownList>
code page:
if(!Page.IsPostBack)
{
sizeDropdown.Items.Add("50g");
sizeDropdown.Items.Add("100g");
}
hey try this i have same issue solve by this....
In desgin add AutoPostBack="True" for dropdownlist.
<asp:DropDownList ID="sizeDropdown" AutoPostBack="True" runat="server" OnSelectedIndexChanged="sizeDropdown_SelectedIndexChanged">
In code behind.....
protected void sizeDropdown_SelectedIndexChanged(object sender, EventArgs e)
{
double amount = 0;
if (sizeDropdown.SelectedItem.Equals("50g"))
{
amount = 4.99;
}
else if (sizeDropdown.SelectedItem.Equals("100g"))
{
amount = 7.99;
}
else if (sizeDropdown.SelectedItem.Equals("150g"))
{
amount = 9.99;
}
priceLabel.Text = amount.ToString();
}
Hope this may be useful to you.

how to maintain dropdownlist selected item after click of a button on the same page

im using an update panel whose update mode is set to conditional. i want to maintain the drop down list selection after I click a button which displays a form to enter information that pertains to that particular selected dropdownlist selection. how can this be done? i enabled view state of the dropdownlist itself to be tru but it isnt working... the list value always goes back to the original default value - 0
<asp:DropDownList ID="DropDownListTug" runat="server" DataSourceID="SqlDataSourceTugs"
DataTextField="Tug_Name" DataValueField="Tug_ID" AutoPostBack="True" AppendDataBoundItems="True"
OnSelectedIndexChanged="ShowNewRateBtn">
<asp:ListItem Value="0" Text="<Select>" Enabled="True" Selected="True"></asp:ListItem>
</asp:DropDownList>
<asp:Button ID="NewTug" runat="server" Text="New Tug" OnClick="NewTug_Click"
CausesValidation="False" Width="74px" />
<asp:SqlDataSource ID="SqlDataSourceTugs" runat="server" ConnectionString="<%$ g %>"
SelectCommand="SELECT [Tug_Name], [Tug_ID] FROM [COMIS_tbl_TugMaster]"></asp:SqlDataSource>
protected void ShowNewRateBtn(object sender, EventArgs e)
{
BtnNewRate.Visible = true;
}
protected void BtnNewRate_Click(object sender, EventArgs e)
{
try
{
processTugs.Visible = true;
allButtons.Visible = true;
BtnSave.Visible = true;
BtnCancel.Visible = true;
// DropDownListTug.Focus();
// DropDownListTug.EnableViewState = true;
// DropDownListTug.SelectedValue = Session.... ;
// }
}
catch (Exception ex)
{
Console.WriteLine("{0} Exception caught.", ex);
}
}enter code here
<asp:ListItem Value="0" Text="<Select>" Enabled="True" Selected="True"></asp:ListItem>
If you see this line in your GridView code i think you are providing a default value to your dropdown everytime it binds .
Your selection will be lost because of this attribute :-
Selected="True"
i made a silly mistake quite really.. in my Cancel function which i called in the New Rate function, i cleared the selection in there. removed it and its working fine now... thanks alot

How do I bind a DropDownList after postback?

I have an aspx site with a DropDownList in it. I want to be able to choose between 3 variables there and then keep the chosen value for the postback. The page is made so that it loads 10 entries from the database and with this DropDownList I want to be able to choose between 10, 20, 30 entries.
DropDownList
<asp:DropDownList ID="dd1" runat="server" AutoPostBack="True" EnableViewState="True">
<asp:ListItem Value="10">10</asp:ListItem>
<asp:ListItem Value="20">20</asp:ListItem>
<asp:ListItem Value="30">30</asp:ListItem>
</asp:DropDownList>
Here I am trying to set the value that is being sent to the database for the query that brings out the 10, 20 or 30 first entries.
public IEnumerable<XX> repOrder_GetData([ViewState]DateTime? UpdatedRows)
{
var ordrar = _facade.OrderGetForAttest(1, Convert.ToInt32(dd1.SelectedValue));
return ordrar;
}
How do I retain this value during a postback because the page will reload every time you choose something in the DropDownList resulting in only the first value ever being chosen.
protected void Page_Init(object sender, EventArgs e)
{
try
{
_masterpage = this.Master as XX.resource.masterpage.Site;
}
catch (Exception)
{
throw;
}
}
protected void Page_Load(object sender, EventArgs e)
{
// Kolla behörighet första gången.
KollaBehorighet();
_masterpage.ClearMessage();
if (Page.IsPostBack)
{
}
else
{
Page.DataBind();
// Första gången..
PageInit();
FillPage(null);
//FIXME: xxx.Focus();
}
}
You should set the 'OnSelectedIndexChanged' event.
<asp:DropDownList ID="dd1" runat="server" AutoPostBack="True" onselectedindexchanged="ddlItemSelected" EnableViewState="True">
<asp:ListItem Value="10">10</asp:ListItem>
<asp:ListItem Value="20">20</asp:ListItem>
<asp:ListItem Value="30">30</asp:ListItem>
</asp:DropDownList>
protected void ddlItemSelected(object sender, EventArgs e)
{
//Add your selected value to viewstate or session or whatever. Then check this value when binding on postback.
Viewstate["myValue"] = dd1.SelectedValue;
}
You can try to store it in Session state and then load it from session
Some like this:
Session["Selected"] = dd1.SelectedIndex;
And in Load Event you can use:
dd1.SelectedIndex = Convert.ToInt32(Session["Selected"]);

Dropdownlist asp.net not working properly

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();

Categories

Resources