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"];
}
}
Related
within my code , after a research via a Formview , I need to call the listview.databind and this makes impossible to get the Formview data , even if in the screen they still appear .
this is my code
protected void DemandeSearchFormView_ItemInserting(object sender, FormViewInsertEventArgs e)
{
ListView listview = (ListView)panelPagination.FindControl("listdeclarations");
ViewState["search"] = "search";
listview.DataBind();
}
the databind() normally call this method
public DeclarationGeneraleBean RechercheByCritere()
{
DeclarationGeneraleBean declarationBean = new
DeclarationGeneraleBean();
declarationBean.IdService = (int) Session["idService"];
if (ViewState["search"] != null)
{
TextBox numOrdre =
(TextBox)DemandeSearchFormView.FindControl("numtxt");
}
the ViewState["search"] is null , I dont know why ?? it seems that the databind() recharge the page or something like this .
Have any one an idea how to deal with this ?
Do you set the viewstate in your page load event?
If yes, i think you should add a condition in your Page_Load event :
private void Page_Load()
{
if (!IsPostBack)
{
}
}
it prevent the data to be reloaded on this event, if a post is submited.
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
I've got a GridView control and Combobox control that are both successfully populated in my Page_Load event (within a block that checks for IsPostBack == false).
I've got an empty button 'btnClick' event handler which will reload the page when clicked. Both the GridView and Combobox controls have their EnableViewState property set to True. The behaviour I was expecting and hoping for was:
Page will reload with the GridView control still populated.
Page will reload with Combobox still populated and the item selected by the user still set as the selected item.
Unfortunately, the behaviour I'm getting is as follows:
GridView control is now empty and shows no data.
Combobox is now empty.
Code as follows:
public MyPage()
{
this.Load += new EventHandler(Page_Load);
}
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == false)
{
DataAccessObj daObj = new DataAccessObj();
foreach (DataRow dataRow in daObj.GetAllData())
{
ListItem listItem = new ListItem(dataRow.ToString(), dataRow.Id.ToString());
myCombobox.Items.Add(listItem);
}
IncidentGrid.DataSource = daObj.GetIncidentsByReportedById(0);
IncidentGrid.DataBind();
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
// Do nothing
}
What I would like to do is allow the user to select an item from the Combobox. Upon clicking Submit, the GridView would be repopulated (based upon the selected item). The Combobox will remain populated and show the last selected item.
Can someone help explain where I might be going wrong? TIA
When you click your button, the page is posted back, in your page load, if it is a postback you need to databind the grid appropriately you need to add a condition to your page load event like
Firstly on your btn_click, you need to store the id selected with something like:
if (myCombobox.SelectedItem != null)
{
if (int.TryParse(myCombobox.SelectedItem.Value, out reportedById) == false)
{
reportedById = 0;
ViewState["reportedById"] = reportedById; // Need to remember which one was selected
}
}
Then On your Post Back
else (IsPostBack)
{
if (ViewState["reportedById"]) != null)
{
IncidentGrid.DataSource = daObj.GetIncidentsByReportedById(Convert.ToInt32(ViewState["reportedById"]));
IncidentGrid.DataBind();
myCombobox.SelectedItem.Value = ViewState["reportedById"].ToString(); // set combo
}
else
{
IncidentGrid.DataSource = daObj.GetIncidentsByReportedById(0);
IncidentGrid.DataBind();
}
}
I am checking some condition in the GridView_RowCommand event. Based on the Condition I want to set SkinID or remove SkinID for the TextBox.
This is my Code:
if (dt.Rows[0]["D1Variable"].ToString() == "0")
{
txtMRVD1.Text = dt.Rows[0]["D1"].ToString();
txtMRVD1.ReadOnly = true;
txtMRVD1.SkinID = "txtreadonly";
}
else
{
txtMRVD1.Text = "";
txtMRVD1.ReadOnly = false;
}
But it throws the following error.
"The 'SkinId' property can only be set in or before the Page_PreInit event for static controls. For dynamic controls, set the property before adding it to the Controls collection."
How to solve this problem?
I would say, based on the error message, that you simply need to move that code to the Page_PreInit event.
However, as MSDN says: "If the request is a postback, the values of the controls have not yet been restored from view state. If you set a control property at this stage, its value might be overwritten in the next event."
You may need to get more creative in how you approach this - perhaps storing the information used to determine the skin id in Session. I suggest getting familiar, if you're not already, with the ASP.NET Page Life Cycle.
Here's an example that might work for you, or at least get you pointed in the right direction:
protected void Page_PreInit(object sender, EventArgs e)
{
if ((string)Session["D1Variable"] == "0")
{
txtMRVD1.SkinID = "txtreadonly";
}
}
You can then do the rest of your logic in the GridView RowCommand event.
(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) {
}
}