Save the dropdowns value when reloading the page? - c#

I have developed a website in ASP.NET that can add articles into a another table that shows a product.
I have a table that displays items in a warehouse and a table showing the materials required to produce a certain product. Using a drop down list you can see which products are manufactured. When the user wants to add to the article, he pushes a button. But after the page loaded on my dropdown list shows the lowest value again instead of keeping its value. Visit the site, change the product (produkt in swedish) from "Cykel" (bicycle) to "car" and add any article and you will understand the problem. Can I do something with page load to find a solution?
Maybe I should mention that I use a datasource that I'm binding the dropdown with.

If you are binding your dropdown in pageload bind it in !ispostback..
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Bind your dropdown
}
}

in onChange of drop down call a function, Assume that is storeValue() function and do somthing like this, [you can add attribute to dropdown as onchange="storeValue(this.value);"]
function storeValue(val)
{
localStorage.setItem("dropdownvalue",val);
}
and
var val="";
$(document).ready(function(){
val=localStorage.getItem("dropdownvalue");
//assign your value to dropdown list from here...
});

With help from the gentlemen above I find out to solve the problem. I used function that is called every time the dropdownlist index is changed. The function save the index in a session.
if (!Page.IsPostBack)
{
try
{
string test = (string)Session["test"];
int value = int.Parse(test);
DropDownList2.SelectedIndex = value;
}
catch
{
}
}
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
Session["test"] = ""+ DropDownList2.SelectedIndex;
}

Related

DataGrid Web Forms EditCommand/UpdateCommand. How to get changed value in TextBox

I've got a problem with my DataGrid's Edit command.
Here's my DataGrid:
http://imgur.com/0nmDJX0
and now i would like to edit my Title:
http://imgur.com/VU20GNa
How can i get the "abc" value?
((TextBox) e.Item.Cells[0].Controls[0]).Text still gives me the old value "sdfsd".
How can i get that "abc" value from textbox? I store my records to XML so all i need is to get these edited values.
Thanks.
Make sure you are not binding your data on every page load. If you do that, your new values are reloaded with old values before your event handler runs.
In my case, I just needed to put the BindData() inside the if (!Page.IsPostBack) block
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindData();
}
}

How do I Grab Selected Index on two Dropdownlist's OnSelectedIndexChanged?

I am trying to use two DropDownLists to filter data. I set both of the OnSelectedIndexChanged Equal to the method below. The problem is it is only grabbing the SelectedIndex of the DDL that is changed. Example: if i choose a option in DDL1 it grabs that value and doesnt grab the value of DDL2. They both have the same OnSelectedIndexChanged i figured it would grab the current value of both. Is there a way to make it look at both DDL Controls?
protected void BrandsList_SelectedIndexChanged(object sender, EventArgs e)
{
int DDLcatId = CategoriesList.SelectedIndex;
int DDLBraId = BrandsList.SelectedIndex;
IQueryable<Product> DDLprodResult = GetProductsDDL(DDLcatId, DDLBraId);
if(DDLprodResult == null)
{
}
else
{
CatLab.Text = DDLprodResult.ToList().Count().ToString();
productList.DataSource = DDLprodResult.ToList();
productList.DataBind();
}
}
Your code should work. Of course only one can be changed if you have set AutoPostBack="true"(default is false) on both. But you should get the correct SelectedIndex anyway in the handler.
So i will guess: you are databinding the DropDownLists on every postback. Do this only if(!IsPostBack), otherwise you always overwrite changes with the original values.
So for example in Page_Load:
protected void Page_Load(Object sender, EvengtArgs e)
{
if(!IsPostBack)
{
// DataBind your DropDownLists
}
}

Having trouble changing field information based on Dropdown list

I think this issue has a simple solution but I have been banging my head on it for a few days now. I have a web application in which Dynamically gets a list of students from a stored procedure. I want to look at detailed information for each student and subsequent class information. On the Student's Details page, there is a dropdown list that contains all the classes that the student is in and when one is selected, the Community Partner field should be updated.
I am using SelectedIndexChanged method but in order to make it work, I need to set AutoPostBack to True and that causes the page to reload and thus the dropdown list and selected value to reload as well. I have tried several different configurations of this code with no results.
Here is my ascx file
<asp:DropDownList ID="StudentCourses" runat="server"></asp:DropDownList>
And here is my ascx.cs file
protected void Page_PreRender(object sender, EventArgs e)
{
if (Session["StudentID"] != null)
{
int studentId = Convert.ToInt32(Session["StudentID"]);
Student student = studentRepository.GetStudent(studentId);
StudentCourses_SelectedIndexChanged(sender, e);
StudentCommunityPartner.Text = StudentCourses.SelectedItem.Value;
...
And here is my SelectedIndexChanged method
protected void StudentCourses_SelectedIndexChanged(object sender, EventArgs e)
{
IList<KeyValuePair<Course, CommunityPartner>> courseList = studentRepository.GetStudentCourses(Convert.ToInt32(Session["StudentID"]));
StudentCourses.DataSource = courseList;
StudentCourses.DataBind();
int ctr = 0;
foreach (KeyValuePair<Course, CommunityPartner> kvp in courseList)
{
if (ctr < StudentCourses.Items.Count)
{
StudentCourses.Items[ctr].Text = kvp.Key.CourseCode;
StudentCourses.Items[ctr].Value = kvp.Value.PartnerName;
ctr++;
}
else ctr = 0;
}
StudentCommunityPartner.Text = StudentCourses.SelectedItem.Value;
}
I have tried several combinations and I am at a loss as to how to properly change the content on the page without the dropdownlist refreshing every time I do. Thanks for your help, it is much appreciated.
To set a textbox off of a drop down change look here:
set dropdownlist value to textbox in jQuery
If you have more that you want to do, the selected value from the drop down should be kept in the view state on post back. You might try saving that value
var Selected = StudentCourses.SelectedValue;
populate the drop down
and then set the selected value with the saved value
StudentCourses.SelectedValue = Selected;

Controls not showing up when added or doubling

I have two textboxes for entering the name and price of an item, a submit button under it, and a bulleted list under that that shows the current items.
On clicking the submit button the new item should be entered in the list of items and the bulleted list refreshed with the new items.
What happens though is that if I put the code that generates the bulleted list in OnInit then the list isn't refreshed on the first postback. If I put it in Page_Load then the list just duplicates itself on every postback. Where am I supposed to put it and what am i doing wrong?
Here is my code.
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
List<Product> Products = (List<Product>)Session["Products"];
foreach (Product p in Products)
{
ListItem productname = new ListItem();
productname.Text = p.name;
blProducts.Items.Add(productname);
}
}
Here is the code of the submit button:
protected void btnSubmit_Click(object sender, EventArgs e)
{
List<Product> Products = (List<Product>)Session["Products"];
string name = txtName.Text;
decimal price = decimal.Parse(txtPrice.Text);
Product p = new Product(name, price);
Products.Add(p);
Session["Products"] = Products;
}
The postback of the buttonclick happens AFTER init, so your order of events is:
Init adds 1 listitem for products
Button click happens, adding to products.
Since products is enumerated before the new item is added, it isn't reflected on your page.
Asp.Net Page Lifecycle Overview
you could move the init code to prerender, since that's the first event after handling postbacks. It may be doubling because you're never clearing that list of items, which, i believe, are stored in ViewState, so every time init gets called (every request), you are adding all of Products again. You could also wrap that section in an if(!Page.IsPostBack) and add directly to the list & the session in your button click, but it's probably better to fix the logic than duplicate the addition code.
Do
Page.IsPostBack == false.
Use:
page_load {
if(!Page.IsPostback)
CalltheLoadFunction
}
on_click {
_adds the stuff.
CalltheLoadFunction() //again
}
CalltheLoadFunction() {
dropdown.clear().
dropdown.datasource = datasource
dropddown.databind()
}
I wouldn't use Init. I use Page_load (ispostback false) in that function. After the button click, call the refresh data function again. You should check ispostback on the page load function all the time. Make sure it is false so that it doesn't load again.

Setting SelectedValue of a data bound DropDownList

I have an asp.net dropDownList which is automatically bound to a sqlDataSource to values of client type on page load. On page load I am also creating a Client object, one of it's properties is ClientType. I am trying to set the SelectedValue of the ddl according to the value of the ClientType property of the Client object unsuccessfully. I recieve the following error message "System.ArgumentOutOfRangeException: 'ddlClientType' has a SelectedValue which is invalid because it does not exist in the list of items". I understand that this is because the list has not yet been populated when I'm trying to set the selected value. Is there a way of overcoming this problem? Thank you!
You have to use the DataBound Event, it will be fired, once databinding is complete
protected void DropDownList1_DataBound(object sender, EventArgs e)
{
// You need to set the Selected value here...
}
If you really want to see the value in the Page load event, then call the DataBind() method before setting the value...
protected void Page_Load(object sender, EventArgs e)
{
DropdownList1.DataBind();
DropdownList1.SelectedValue = "Value";
}
Before setting a selected value check whether item is in list and than select it by index
<asp:DropDownList id="dropDownList"
AutoPostBack="True"
OnDataBound="OnListDataBound"
runat="server />
protected void OnListDataBound(object sender, EventArgs e)
{
int itemIndex = dropDownList.Items.IndexOf(itemToSelect);
if (itemIndex >= 0)
{
dropDownList.SelectedItemIndex = itemIndex;
}
}
EDIT: Added...
If you are doing binding stuff in Page Load, try to follow this way:
Move all binding related code in overriden DataBind() method
In Page_Load of Page add: (in case of control do not call DataBind directrly, this is a responsibility of a parent page)
if (!IsPostBack)
{
Page.DataBind(); // only for pages
}

Categories

Resources