Dropdownlist asp.net not working properly - c#

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

Related

Dynamically change radiobuttonlist name in asp.net

In my aspx file, I have a drop down list
<asp:DropDownList runat="server" ID="Dlist" CssClass="dropdown" AutoPostBack="true" SelectedIndexChanged="CtrlChanged">
<asp:ListItem Text="Select item" Value="1"></asp:ListItem>
</asp:DropDownList>
I have a radio button list
<asp:RadioButtonList ID="RadioButtonList1" RepeatColumns="1"
RepeatDirection="Vertical" RepeatLayout="Table" runat="server" AutoPostBack="true">
<asp:ListItem>Option 1</asp:ListItem>
<asp:ListItem>Option 2</asp:ListItem>
</asp:RadioButtonList>
Now I want to change the name of one or both of the radio buttons in the radio button list after something has been selected from the dropdown list using C#. Below is my attempt but not working.
protected void CtrlChanged(Object sender, EventArgs e) {
//attempting to change text of first radio button when item has been selected from dropdownlist
RadioButtonList1.SelectedIndex = 0;
RadioButtonList1.SelectedItem.Text = "Text changed!";
}
First, it is OnSelectedIndexChanged, not SelectedIndexChanged. And the ListItems of a RadioButtonList are index based, so you need to access them like this:
protected void CtrlChanged(object sender, EventArgs e)
{
RadioButtonList1.Items[0].Text = "NewValue 1";
RadioButtonList1.Items[1].Text = "NewValue 2";
}
Your way does change the text, but only for the item you set the SelectedIndex of. And it will change the selected radiobutton to the first one, should one already have been selected.

How to get Dropdowns selected text where there are multiple dropdowns

I have multiple dropdowns like this
<asp:DropDownList ID="ddl1"
runat="server"
DataTextField="Text"
DataValueField="ValID"
AutoPostBack="true"
OnSelectedIndexChanged="ddl_SelectedIndexChanged">
</asp:DropDownList>
<asp:DropDownList ID="ddl2"
runat="server"
DataTextField="Text"
DataValueField="ValID"
AutoPostBack="true"
OnSelectedIndexChanged="ddl_SelectedIndexChanged">
</asp:DropDownList>
Both the dropdowns has different set of values they are unique. I did the following on ddl_SelectedIndexChanged funtion
DropDownList ddl = sender as DropDownList;
string selectedId = ddl.ID;
string selectedText = ddl.SelectedItem.Text;
When I select values on the first dropdown I get correct selectedId and selectedText.
My Problem:
When I select the second dropdown the selectedId is of the second dropdown but selectedText is always the first dropdowns first value and it never changes. I need selectedText to be that of the Item which I select in the second dropdown.
Any Suggestion?
When binding the data to the DropDownLists, you must place them inside an IsPostBack check.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ddl1.DataSource = source;
ddl1.DataBind();
ddl2.DataSource = source;
ddl2.DataBind();
}
}
If you do not the SelectedIndexChanged will fire each time for the DropDownList because rebinding data will trigger that since the previous selecedindex is overwritten.

Enabling & Disabling Drop Down Lists

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.

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 to Bind SelectedValues of DataBase values to Dropdown list in a Grid?

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.

Categories

Resources