It is a very weird problem
when I change the value of the drop down list, a new drop down list is show. I am so confused,
To know what I am talking about, please check these images.
edit
code for bind
CallerId = Request["CallerID"];
if (String.IsNullOrWhiteSpace(CallerId)) return;
var results = ZumaDa.GetCustomerInformation(CallerId);
rowCount = results.Rows.Count;
CallerId = rowCount > 0 ? results.Rows[0][4].ToString() : CallerId;
if (rowCount > 1)
{
ListView1.Enabled = false;
GridView1.DataSource = results;
GridView1.DataBind();
}
else
{
GridView1.Enabled = false;
ListView1.DataSource = results;
ListView1.DataBind();
}
That code is in page load and NOT on !ispostback
Since you updated your question with the ListView markup, and your Page_Load code, it appears the problem of the duplicated DropDownList goes away after you wrap your databinding code in an if (!Page.IsPostBack) block.
One problem in your code is that, in your SelectedIndexChanged event, you're searching the ListView for your DropDownList and TextBox. You need to search the ListViewItem control where the SelectedIndexChanged event occurred.
To do that, you can first get the DropDownList from the "sender" parameter. Then you should find the "NamingContainer" control of the DropDownList, and search that. Like this:
var dropDown = (DropDownList)sender;
var visitID = (TextBox)dropDown.NamingContainer.FindControl("visitID");
That second line of code might need to have an additional ".NamingContainer" depending on your markup.
I think you need to bind listview in !IsPostback check means when do postback it pageload event fired and it bind dropdown with second time or if its not please share binding code
Related
I have a column in a GridView which has a Dropdownlist in the EditTemplate
The data for this dropdownlist is added dynamically (items.add()) after the user enters the edit mode for that row.
foreach (var bgElement in userCropList.FirstOrDefault(c => c.Crop == cropToBeUpdated).BGs)
{
ddl.Items.Add(bgElement.BG);
}
ddl.SelectedIndex = userCropList.FirstOrDefault(c => c.Crop == cropToBeUpdated).BGs.FindIndex(d => d.Default == true);
When the user clicks the update button to save his changes, the page does a postback and as such lose the items aswell as the selectedindex which i need for the following bit in the RowUpdating event.
DropDownList ddl = (DropDownList)GVCrops.Rows[e.RowIndex].FindControl("ddlAvailableBGs");
updatedCrop.BGs.FirstOrDefault(c => c.BG == ddl.SelectedValue).Default = true;
What came to my mind was to put the value the user selects in a viewstate variable and read from it in the RowUpdating event.
I am asking if there is an easier (not that it is hard) or already available thing that I am missing which could that for me?
Edit:
Ok, turns out my method ..
RowEditing():
ViewState.Add("SelectedBGIndex", ddl.SelectedValue);
RowUpdating():
if (ViewState["SelectedBGIndex"] != null)
{
updatedCrop.BGs.FirstOrDefault(c => c.BG == ViewState["SelectedBGIndex"].ToString()).Default = true;
}
..is not going to work for the same reason apparently.
When the user clicks the update button for the row it will post back and the drop down list is reset with no selection and no items inside.
Seems like the solution would be a JavaScript function.
Any thoughts how to approach it?
I have three drop down menus that are using a store Procedure to populate my gridview. I need the first facility DropDown to give different options in the second source type dropdown depending on what facility is selected. Some facility's need to see all options and some only 1 or 2. I am unsure how to go about this.
Here is the code for the dropdowns and the store precedure.
Any help would be greatly appreciated
private void BindGrid()
{
//set up arguments for the stored proc
int? FacilityID = (ddlFacility.SelectedValue.Equals("-1")) ? (int?)null : int.Parse(ddlFacility.SelectedValue);
int? SourceTypeID = int.Parse(ddlSource.SelectedValue);
int? StatusTypeID = int.Parse(ddlStatusType.SelectedValue);
//bind
ObjectResult<models.MS_spGetMatchCross_Result> ds = this.DataLayer.model.MS_spGetMatchCross(FacilityID, SourceTypeID, StatusTypeID);
gvResults.DataSource = ds;
gvResults.DataBind();
}
private void ResetForm()
{
try
{
//facility dropdown
ddlFacility.Items.Clear();
ddlFacility.DataSource = this.DataLayer.model.MS_spGetFacilityInfo(null).OrderBy(x => x.FacilityName);
ddlFacility.DataTextField = "FacilityName";
ddlFacility.DataValueField = "FacilityID";
ddlFacility.DataBind();
ddlFacility.Items.Insert(0, new ListItem("Select a facility...", "-1"));
//SourceType dropdown
ddlSource.Items.Clear();
ddlSource.DataSource = this.DataLayer.model.SourceTypes;
ddlSource.DataTextField = "Description";
ddlSource.DataValueField = "SourcetypeID";
ddlSource.DataBind();
//Match Status dropdown
ddlStatusType.Items.Clear();
ddlStatusType.DataSource = this.DataLayer.model.StatusTypes;
ddlStatusType.DataTextField = "Description";
ddlStatusType.DataValueField = "StatusTypeID";
ddlStatusType.DataBind();
BindGrid();
}
catch (Exception ex)
{
this.SetMessage(ex.ToString(), PageMessageType.Error);
AISLogger.WriteException(ex);
}
}
A very straightforward, though not exactly elegant, way would be to handle the DropDownList's OnSelectedIndexChanged event. For that to work, you'd have to make sure that each DDL whose selection will affect the contents of another DDL has the AutoPostBack property set to true (this ensures when something in the DDL changes, the page will cause a postback, allowing you to handle the change in server-side code).
In your first DropDownList's OnSelectedIndexChanged event handler (in the code-behind), you'll have the following code:
// Handle selected item or selected index
if(ddl1.SelectedItem.Text=="Selection1")
{
// Get items for DDL2
var items=GetDataForDdl2();
// Bind the data
DDL2.DataSource=items;
DDL2.DataBind();
}
You'd have similar logic for DDL2's SelectedIndexChanged event handler to then bind the items of DDL3, and so on.
For something that works nicely out of the box, check out the ASP.NET AJAX AjaxControlToolkit's CascadingDropDown: http://www.asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/CascadingDropDown/CascadingDropDown.aspx
Could someone help me with this solution, stuck on it.
I have a list and filling radiobuttonlist with data, but I can't get selected value when i press submit button.
List<CustMobilePhonesEntity> cusMobile = GetCusMobile(Email);
RadioButtonList1.Items.Add(customerMobile[0].PhoneNumber);
RadioButtonList1.DataSource = customerMobile;
RadioButtonList1.DataTextField = "PhoneNumber";
RadioButtonList1.DataValueField = "PhoneNumber";
RadioButtonList1.DataBind();
Label1.Text = RadioButtonList1.SelectedValue;
Any ideas what I'm doing wrong, thank you.
First you need to check you are doing it in this fashion (If not the list is again binded with the DataSource when you click submit and the selection is lost)
if(! IsPostBack)
{
RadioButtonList1.DataSource = customerMobile;
RadioButtonList1.DataTextField = "PhoneNumber";
RadioButtonList1.DataValueField = "PhoneNumber";
RadioButtonList1.DataBind();
}
Also since you are binding RadioButtonList1.Items.Add(customerMobile[0].PhoneNumber); this won't be required (not clear if anything else).
Also see that ViewState is enabled
I would like some help with the following problem. I have a dropdownlist implemented in my masterpage. It has an sql data source from which it loads the values of companies. Depending on which value(company) selected, it shows that value in a label on a different page.
The ddl which is in the masterpage is ofc still visible and should display the selected value which it does at the 1st time a value is selected. But when i select another value in the ddl it shows the value which was 1st selected and so on. So it doesn't update or something.
My code:
This is the onselectedIndexChanged event handler:
protected void DropDownListType_SelectedIndexChanged(object sender, EventArgs e)
{
String input1 = DropDownListType.Text;
String input2 = DropDownListType.SelectedValue;
String url = "~/test.aspx?pcompany="+input1;
DropDownListType.SelectedValue = input2;
Session["Company"] = input2;
Response.Redirect(url);
}
and this is the code i'm using in my Page_load method from the masterpage:
if (Session["Company"] != null)
{
DropDownListType.SelectedValue = (String)Session["Company"];
}
If I remove this last piece of code from my page_load method it updates the label with value on the redirected page but it resets my ddl to default value instead of keeping it at 4 when value 4 selected.
I hope this is a bit clear to you all. Any help is appreciated. Ty in advance.
try setting the label value in the PreRender() method. The problem you're having is with the page life cycle. I would change your OnLoad method to use
if(!IsPostBack) {
if (Session["Company"] != null)
{
DropDownListType.SelectedValue = (String)Session["Company"];
}
}
This way you're only setting it once when the page loads and from then on the page will set the selected value automatically using viewstate.
The Load event is fired before the SelectedIndexChanged event, that's why you don't have it set in Session yet.
See ASP.NET Page Life Cycle
just set the AutoPostback property of the DropDownList to true and then it will work.
This is because otherwise the onselectedIndexChanged will be called only on PostBack from a button or any other field.
And also, as the above answer says, use this code:
if(!IsPostBack) {
if (Session["Company"] != null)
{
DropDownListType.SelectedValue = (String)Session["Company"];
}
}
(Scroll down to bottom of post to find solution.)
Got a asp.net page which contains a
Datalist. Inside this datalist, there
is a template containing a
dropdownlist and each time the
datalist is filled with an item, a
ItemCreatedCommand is called. The
itemCreatedCommand is responsible for
databinding the dropdownlist.
I think the problem lies here, that
I'm using ItemCreatedCommand to
populate it - but the strange things
is that if I choose the color "green",
the page will autopostback, and I will
see that the dropdown is still on the
color green, but when trying to use
it's SelectedIndex, I always get 0...
protected void DataListProducts_ItemCreatedCommand(object
source, DataListItemEventArgs e)
var itemId = (String)DataListProducts.DataKeys[e.Item.ItemIndex];
var item = itemBLL.GetFullItem(itemId);
var DropDownListColor = (DropDownList)e.Item.FindControl("DropDownListColor");
//Also tried with :
//if(!isPostBack) {
DropDownListColor.DataSource = item.ColorList;
DropDownList.Color.Databind();
// } End !isPostBack)
Label1.test = DropDownListColor.SelectedIndex.toString();
// <- THIS IS ALWAYS 0! *grr*
I've narrowed down the code a bit for
viewing, but still you can see what
I'm trying to do :) The reason for
why I'm doing this, and not declaring
the datasource for the colors directly
i aspx-page, is that I need to run a
test if(showColors), but I do not want
to clutter up the html-page with code
that I feel should be in the code
behind-file.
EDIT: After trying to alter
SelectedIndexChange - I'm having a
"logical" confusion in my head now -
how am I to alter elements inside the
datalist? Since, as far as I know - I
do not have any way to check which of
the items in the datalist this
particular dropdownlist belongs to...
Or? I'm going to try out a few ways
and see what I end up with ;) But do
please post your thoughts on this
question :)
SOLUTION:
Either bubble the event to ItemCommand, or Handle the event, get the senders parent(which is a datalistItem and manipulate elements in there.
protected void DropDownListColor_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList dropDownListColor = (DropDownList)sender;
DataListItem dataListItem = (DataListItem)dropDownListColor.Parent;
var item = items[dataListItem.ItemIndex];
var color = item.ItemColor[dropDownListColor.SelectedIndex];
var LabelPrice = (Label)dataListItem.FindControl("LabelPrice");
LabelPrice.Text = color.Price;
}
When the DataList is data-bound, the AutoPostBack has not been handled yet, i.e. the values in the ItemCreated event are still the original values.
You need to handle the SelectedIndexChange event of the dropdown control.
Regarding your 2nd question:
I suggest you remove the AutoPostBack from the dropdown, add an "Update" button, and update the data in the button Click event.
The button can hold Command and CommandArgument values, so it's easy to associate with a database record.
some MSDN links with C# examples on bubbling
http://msdn.microsoft.com/en-us/library/system.web.ui.control.onbubbleevent.aspx
http://msdn.microsoft.com/en-us/library/aa719644(VS.71).aspx
http://msdn.microsoft.com/en-us/library/aa720044(VS.71).aspx
Thank You for your solution
protected void ddlOnSelectedIndexChanged(object sender, EventArgs e) {
try {
ModalPopupExtender1.Show();
if (ViewState["Colors"] != null) {
FillColors(ViewState["Colors"].ToString());
}
DropDownList dropDownListColor = (DropDownList)sender;
DataListItem dataListItem = (DataListItem)dropDownListColor.Parent;
Image image = (Image)dataListItem.FindControl("mdlImage");
Label ProductCode = (Label)dataListItem.FindControl("lblprdCode");
Label ProductName = (Label)dataListItem.FindControl("lblProdName");
DropDownList ddlQuantity = (DropDownList)dataListItem.FindControl("ddlQuantity");
Label ProductPrice = (Label)dataListItem.FindControl("lblProdPrice");
Label TotalPrice = (Label)dataListItem.FindControl("lblTotPrice");
//Label ProductPrice = (Label)dataListItem.FindControl("lblProdPrice");
} catch (Exception ex) {
}
}