How to get Dropdowns selected text where there are multiple dropdowns - c#

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.

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.

Getting pre-selected Text in dropdown in EditItemTemplate gridview

I am not able to get preselected text in dropdown in edit template. Please see my code:
<EditItemTemplate>
<asp:DropDownList ID="droplist" runat="server">
</asp:DropDownList>
</EditItemTemplate>
c# code
protected void gvDetails_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
DropDownList droplist = (DropDownList)e.Row.FindControl("droplist");
droplist.DataSource = EquipmentBLL.getunitdrop();
droplist.DataTextField = "UnitName";
droplist.DataValueField = "UnitID";
droplist.DataBind();
droplist.Items.Insert(0, new ListItem(" Select Unit ", "0"));
//droplist.Items.FindByText(unittypetext).Selected = true;
}
}
}
Can someone tell me what I should do to get preselected dropdown?
regards
Hussain
Right now, you're populating the DropDownList with options from a datasource. However, you're not binding it's selected value to anything.
Whatever you are doing to bind the other fields in your Gridview, do that for the DropDownList's SelectedValue as well.
Without seeing the rest of your GridView markup, I'm thinking something like this should work:
<EditItemTemplate>
<asp:DropDownList ID="droplist" runat="server"
SelectedValue='<%# Bind("UnitID") %>' >
</asp:DropDownList>
</EditItemTemplate>
Where "UnitID" above is the name of the field from your GridView's datasource that you want to bind to the SelectedValue of the DropDownList.

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

Radio button does not return selected value

i am using radio button list control in asp.net.
i m trying to get selected value on button click Event
but,i m getting Empty string and i want it without javascript.
How can i do this?
<asp:RadioButtonList ID="RadioButtonList1" EnableViewState="true" runat="server"
Width="287px">
<asp:ListItem Value="Single" runat="server" Text="Single"></asp:ListItem>
<asp:ListItem Value="Jointly" runat="server" Text="Married Filing Jointly/Widower"></asp:ListItem>
<asp:ListItem Value="Separately" runat="server" Text="Married Filing Separately"></asp:ListItem>
<asp:ListItem Value="Household" runat="server" Text="Head Of Household "></asp:ListItem>
</asp:RadioButtonList>
C# code
protected void btnCalculate_Click(object sender, EventArgs e)
{
string selectedValue = RadioButtonList1.SelectedValue;
}
When you bind your RadioButtonList, you can place your code in ! IsPostback , in order to don't erase your `selected value, when you post your control (click event).
Page_Load :
if(! isPostBack)
{
//Bind your radioButtonList
}`
Nota : You persist your datas with ViewState
first check your postback event in your page_load..then you can use RadioButtonList1.SelectedValue
Or You could use :--
string selectedValue = RadioButtonList1.SelectedValue.ToString();
Remarks from MSDN for RadioButttonList SelectedValue
This property returns the Value property of the selected ListItem. The
SelectedValue property is commonly used to determine the value of the
selected item in the list control. If multiple items are selected, the
value of the selected item with the lowest index is returned. If no
item is selected, an empty string ("") is returned.
So suggest #1 is that you atleast make on the item as default selection by using the attribute Selected="true"
Suggestion #2 will be (just a opinion) for the sake of readability use SelectedItem.Value
protected void btnCalculate_Click(object sender, EventArgs e)
{
string selectedValue = RadioButtonList1.SelectedItem.Value;
}

asp.NET Drop Down List within a Grid View - Getting the selected value

I have a status drop down list which I am using within a grid view, the users can select a list item they want when editing a row within the grid view. The problem is that the current implementation is not retrieving the selected value, but is only retrieving the default/loaded value.
This is the defination of the grid view:
<asp:GridView ID="applicationGrid" runat="server" Width="95%"
AutoGenerateEditButton="True"
AutoGenerateColumns="False"
ShowFooter="True"
CellSpacing="10"
HeaderStyle-HorizontalAlign="Left"
ItemStyle-HorizontalAlign="Left"
OnRowUpdating="applicationGrid_RowUpdating"
OnRowEditing="applicationGrid_RowEditing"
OnRowCancelingEdit="applicationGrid_RowCancelingEdit"
AutoPostBack="true" >
And this is the defination of the Column where the dropdown list will appear on edit:
<asp:TemplateField HeaderText="Status">
<ItemTemplate>
<asp:Label ID="StatusDescription" runat="server" Text='<%# Eval("STATUS_DESCRIPTION") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="StatusDescriptionList" runat="server" DataTextField="status_description"
DataValueField="application_status_code" OnLoad="DropDownLoadEdit">
<asp:ListItem Text="Status:" Value="default"></asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
This is the code behind which is handling the update scenario:
protected void applicationGrid_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = applicationGrid.Rows[e.RowIndex];
applicationGrid.EditIndex = -1;
Label applicationCodeLabel = row.FindControl("AppID") as Label;
TextBox applicationNameTextBox = row.FindControl("AppNameEdit") as TextBox;
TextBox applicationURLTextBox = row.FindControl("AppURLEdit") as TextBox;
DropDownList applicationStatusDropDownList = row.FindControl("StatusDescriptionList") as DropDownList;
int applicationCode = Convert.ToInt32(applicationCodeLabel.Text);
string applicationName = applicationNameTextBox.Text;
string applicationURL = applicationURLTextBox.Text;
int applicationStatus = Convert.ToInt32(applicationStatusDropDownList.SelectedValue.ToString());
//string applicationStatus2 = applicationStatusDropDownList.SelectedItem.Value;
//string applicationStatus3 = applicationStatusDropDownList.SelectedItem.Text;
application.UpdateApplication(applicationCode, applicationName, applicationURL);
PopulateApplications();
}
All is working, but the selected value is not the one which the is loaded and not the one which the user selects. Therefore the problem is getting the selected value from the list. What needs to be changed, and why?
protected void applicationGrid_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = applicationGrid.Rows[e.RowIndex];
applicationGrid.EditIndex = -1;
Label applicationCodeLabel = row.FindControl("AppID") as Label;
TextBox applicationNameTextBox = row.FindControl("AppNameEdit") as TextBox;
TextBox applicationURLTextBox = row.FindControl("AppURLEdit") as TextBox;
DropDownList applicationStatusDropDownList = row.FindControl("StatusDescriptionList") as DropDownList;
int applicationCode = Convert.ToInt32(applicationCodeLabel.Text);
string applicationName = applicationNameTextBox.Text;
string applicationURL = applicationURLTextBox.Text;
int applicationStatus = Convert.ToInt32(applicationStatusDropDownList.SelectedValue.ToString());
//string applicationStatus2 = applicationStatusDropDownList.SelectedItem.Value;
//string applicationStatus3 = applicationStatusDropDownList.SelectedItem.Text;
application.UpdateApplication(applicationCode, applicationName, applicationURL);
PopulateApplications();
}
EDIT: Adding my Populate Methods:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
try
{
PopulateApplications();
}
catch (Exception exception)
{
throw exception;
}
}
}
private void PopulateApplications()
{
DataTable reader = application.GetApplicationList();
applicationGrid.DataSource = reader;
applicationGrid.DataBind();
applicationGrid.AllowSorting = true;
}
protected void DropDownLoadEdit(object sender, EventArgs e)
{
DataTable statusTable = application.GetStatusList();
DropDownList dropdown = sender as DropDownList;
dropdown.DataSource = statusTable;
dropdown.DataTextField = "status_description";
dropdown.DataValueField = "application_status_code";
dropdown.DataBind()
}
Update #2: I am trying to fill up a static variable in the class which is for the selected index. This will then be used when update is pressed. However, this is still getting the original value of the drop down list and not the selected one.
This is the method:
protected void StatusDescriptionList_SelectedIndexChanged(object sender, System.EventArgs e)
{
DropDownList ddl = (DropDownList)sender;
selectedValue = Convert.ToInt32(ddl.SelectedValue.ToString());
}
Are you repopulating the list in DropDownLoadEdit, regardless of whether the transition is a postback or not? If so, the list will be repopulated before its value is read, and set to the default before your method has a chance to read the value.
The issue may be of the post back.
Once the item is selected from the drop down the page get post back the value you selected get vanished.
To over come this issue. Bind the drop down list inside page is post back or else make use of a Ajax update panel.
#Ryan, Have you done this
'
AutopostBack="True"
<asp:DropDownList ID="StatusDescriptionList" runat="server" AutopostBack="True" DataTextField="status_description"
DataValueField="application_status_code" OnLoad="DropDownLoadEdit">
<asp:ListItem Text="Status:" Value="default"></asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="StatusDescriptionList" runat="server" DataTextField="status_description"
DataValueField="application_status_code" SelectedValue="application_status_code" AutopostBack="True" OnLoad="DropDownLoadEdit">
<asp:ListItem Text="Status:" Value="default"></asp:ListItem>
</asp:DropDownList>

Categories

Resources