I've this program with two web forms. I take the data from one of the web forms through
public GigOpportunity GetData()
{
//Get written data from text boxes from this web form to the other
return new GigOpportunity(txtBoxID.Text, Calendar1.SelectedDate.Date,
TextBoxVenue.Text, TextBoxGenre.Text, Convert.ToDouble(TextBoxCost.Text),
Convert.ToInt32(TextBoxCapacity.Text), CheckHeadLiner.Checked,
TextBoxMainAct.Text, CheckEngineer.Checked);
}
public void ButtonOk_Click(object sender, EventArgs e)
{
// First part: Saves info on first page.
Session.Add("Gig", GetData());
// First part: Saves info on first page.
GigManagerWebForm.add = true;
Server.Transfer("~/GigManagerWebForm.aspx");
}
And I get it to another form through this,
private void Page_Load(object sender, EventArgs e)
{
gigList = new GigList();
AddGig();
}
private void UpdateList()
{
lstGigs.Items.Clear();
for (int i = 0; i < gigList.Count(); i++)
{
lstGigs.Items.Add(Convert.ToString(gigList.getGig(i)));
}
}
public void AddGig()
{
if (add == true)
{
//Reads info into variables on the second page.
GigOpportunity getData = (GigOpportunity)(Session["Gig"]);
gigList.addGig(getData);
add = false;
//Create new session ID
Session.Abandon();
Response.Cookies.Add(new HttpCookie("ASP.NET_SessionId", ""));
}
UpdateList();
}
I simply have no clue why my list only shows me the one item that I lastly add.
In Page_Load you initalize a new GigList to the gigList variable. In AddGig you add a new GigOpportunity to it.
Then in UpdateList, you clear the lstGigs, and add whatever is in gigList to it. There's only one item in gigList, which is the one you just added. That's the reason you're only seeing the last item.
Where and how is lstGigs initialized? It should be populated from some kind of storage before you try to add the new item.
This is because in UpdateList method you clears out the list and you add elements from gigList but on every Page_Load gigList becames new List and addGig adds to it only one item. To resolve the issue you have you probably ought to not clear the ListBox before you add new element. Alternatively you might want to store whole list (not only last added element) in a session. You might as well save that List to ViewState.
I tried the following simplified code on my application and it worked:
public void ButtonOk_Click(object sender, EventArgs e)
{
// First part: Saves info on first page.
if (Session["Gig"] == null)
{
Session.Add("Gig", new List<string>());
}
List<string> list = (List<string>)Session["Gig"];
list.Add("new Data");
Session["Gig"] = list;
Server.Transfer("~/GigManagerWebForm.aspx");
}
// On the GigManagerWebForm.aspx
private void Page_Load(object sender, EventArgs e)
{
AddGig();
}
public void AddGig()
{
if(Session["Gig"] != null)
{
//Reads info into variables on the second page.
List<string> getData = (List<string>)(Session["Gig"]);
ListBox1.Items.AddRange(getData.Select(d => new ListItem(d)).ToArray());
Session["Gig"] = getData;
}
}
Related
I have the following Problem, i created a C# User Control with a couple of Input fields.
I implemented 2 Main functions ( Set_Data and Read_Data).
Set Data Reads some Data from a Class and Displays it at the User_Control.
Read_Data: Reads the Input value and stores it inside the same Class.
These functions are tested and work properly.
But if i try to use the same User Control to store the Data into another Instance of the same class the Information in the first Class stores the values of the second one too.
Maybe im just doing something wrong.
private Data_Class DataClass1 = new Data_Class();
private Data_Class DataClass2 = new Data_Class();
private void btn_page1_Click(object sender, EventArgs e)
{
page = "page1";
UserControl1.set_Data(DataClass1);
UserControl1.BringToFront();
}
private void btn_page2_Click(object sender, EventArgs e)
{
page = "page2";
UserControl1.set_Data(DataClass2);
UserControl1.BringToFront();
}
private void check_pagechange_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (page != last_page)
{
if (last_page == "page1")
{
DataClass1 = UserControl1.read_Data();
}
if (last_page == "page2")
{
DataClass2 = UserControl1.read_Data();
}
last_page = page;
}
}
As it can be seen i use a Backgroundworker which reads the Data from the Usercontrol when there is a Pagechange.
I have two forms that need to interact with each other. The parent form has 4 fields and an add button that saves data from each field to an instance of a class object. After its saved to an object the object is stored in a listbox, which the child form contains. I created a custom event to handle that stuff, but I am surely doing something wrong.
What's supposed to happen is that when both windows are open, and there is data in the listbox, whatever item that is selected from the child form listbox fills the parent form fields with the data from that object. When I test out my code, only the first item has the data properly filling the correct fields. If I click any other item after the first selection, the main form fields do not update at all.
Specific to my issue the child form has the following codes:
public EventHandler ListBoxItemClicked;
private void pPotionList_SelectedIndexChanged(object sender, EventArgs e)
{
PotionForm tempMain = new PotionForm(); //this was a test, nothing changed
pPotionList.SelectionMode = SelectionMode.One;
if (ListBoxItemClicked != null)
{
ListBoxItemClicked(this, new EventArgs());
}
tempMain.Refresh(); // this too
}
The parent form has these codes
private void pListDisplay_Click(object sender, EventArgs e)
{
PotionList secForm = new PotionList();
secForm.secFormBox.DataSource = potionBindList;
PotionListChanged += secForm.HandlePotionListChanged;
secForm.ChildPotionListChanged += HandleChildPotionListChanged;
secForm.ListBoxItemClicked += HandleListBoxItemClicked; //this line
secForm.Show();
}
public void HandleListBoxItemClicked(object sender, EventArgs e)
{
pTypeInput.SelectedItem = aPotion._type;
pMagInput.Value = aPotion._magnitude;
pNameInput.Text = aPotion._name;
pBonusInput.Checked = aPotion._bonus;
}
I am currently using Visual Studio Community 2015 if that's relevant.
Ok after seeing all the necessary code I would say that the problem is that you never pass the values from the Child-Form to the Parent. Whenever the event HandleListBoxItemClicked is fired only the initial values of aPotion are written to the controls.
As a solution I would suggest to pass the SelectedItem as the sender when you fire the ListBoxItemClicked event in the childform:
CHILD
public EventHandler ListBoxItemClicked;
private void pPotionList_SelectedIndexChanged(object sender, EventArgs e)
{
Potion p = pPotionList.SelectedItem as Potion;
pPotionList.SelectionMode = SelectionMode.One;
if (p != null)
{
if (ListBoxItemClicked != null)
{
ListBoxItemClicked(p, new EventArgs());
}
}
}
Not you can use this information in the parent form and disperse the information as you please:
PARENT
public void HandleListBoxItemClicked(object sender, EventArgs e)
{
Potion p_parent = sender as Potion;
if(p_parent != null)
{
pTypeInput.SelectedItem = p_parent._type;
pMagInput.Value = p_parent._magnitude;
pNameInput.Text = p_parent._name;
pBonusInput.Checked = p_parent._bonus;
}
}
No refresh or anything else should now be necessary. Hope it helps
I have a checkbox list and a button on page 1, a label and a button on page 2. What I'm trying to do is remember what checkboxes were checked, when returning to page1 from page 2.any ideas? I'm lost here's my code. I tried making a collection but that didn't work? Or should a array be used??
Page1.aspx
namespace Form
{
public partial class Page2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string daysrequested = "";
int count = 0;
foreach (ListItem daysItem in Checkboxlist1.Items)
{
if (daysItem.Selected)
{
daysrequested += " <br /> " + daysItem.Value;
count++;
}
}
Session["daysre"] = daysrequested;
Response.Redirect("Page2.aspx");
}
Page2.aspx
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Form
{
public partial class Page21 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string days = (string)Session["daysre"];
daysLabel.Text = String.Format("You picked" + days);
}
protected void btn_Click(object sender, EventArgs e)
{
Response.Redirect ( "Page1.aspx");
}
}
}
Do not use a string as the data type to hold the check box list items' value, but rather a List<string>, since ListItem's Value property is a string, like this:
protected void Button1_Click(object sender, EventArgs e)
{
List<string> daysrequested = new List<string>();
foreach (ListItem daysItem in Checkboxlist1.Items)
{
if (daysItem.Selected)
{
daysrequested.Add(daysItem.Value);
}
}
Session["daysre"] = daysrequested;
Response.Redirect("Page2.aspx");
}
Now in the Page_Load of page 2, you can pull the list out of Session, like this:
protected void Page_Load(object sender, EventArgs e)
{
List<string> requestedDays = new List<string>();
requestedDays = Session["daysre"] as List<string>;
StringBuilder theRequestedDaysStringBuilder = new StringBuilder();
foreach(string day in requestedDays)
{
theRequestedDaysStringBuilder.Append(day);
}
daysLabel.Text = String.Format("You picked" + theRequestedDaysStringBuilder.ToString());
}
Finally, to recheck the check boxes in page 1, do this in the Page_Load:
protected void Page_Load(object sender, EventArgs e)
{
// Check to see if daysre is in session cache
if(Session["daysre"] != null)
{
// Get list from session cache
List<string> requestedDays = new List<string>();
requestedDays = Session["daysre"] as List<string>;
// Loop through each value in list
foreach(string day in requestedDays)
{
theRequestedDaysStringBuilder.Append(day);
// Loop through each item in check box list
foreach (ListItem daysItem in Checkboxlist1.Items)
{
// Check to see if this item needs to be checked by
// comparing its value with current value in list
if(daysItem.Value == day)
{
// We have a match
// Make item checked and break out of loop
daysItem.Checked = true;
break;
}
}
}
}
StringBuilder theRequestedDaysStringBuilder = new StringBuilder();
foreach(string day in requestedDays)
{
theRequestedDaysStringBuilder.Append(day);
}
daysLabel.Text = String.Format("You picked" + theRequestedDaysStringBuilder.ToString());
}
On Page 1 :
On Button Click store the checked values of Check List in a session
and also assign one more session("Page2Visited")="1"
in page_load function
if session("Page2Visited") = "1" then
assign all stored session values as checked to check list
else
keep all values in checklist as unchecked
end if
clear all sessions
First of all, it's not pretty well idea to keep your selected items inside a string variable and later store in Session object. You can add them into an array or generic list. Later, you can format your display string (inside page_load method of Page2 page) reading your array items.
If you back to page1, your items won't be selected because you haven't handle it. You will need to read your previously setup Session object and select chosen items (inside Page1 Page_Load method) .
I just made a solution to reproduce the error, copied pasted your whole code but didnt get any error, in fact its working exactly as u want
So maybe check once the page number
Cause the code you provided says
public partial class Page21 : System.Web.UI.Page
On your Page2
What I am trying to do is to keep the value in an array until I clear it out after the SendEmail(). Seems that the Session Array is getting overwritten. Any help with be great.
So what I mean is to Add another Record to the ArrayList until I clear it out in the SendEmail() routine.
Of course later I would need to remove the duplicate records in the ArrayList.
Here is my C# 2.0 code:
In Login.cs
public void Page_Load(object sender, EventArgs e)
{
Session["MyArrayList"] = null;
}
In Share.cs
public void Page_Load(object sender, EventArgs e)
{
ArrayList idList = new ArrayList();
idList.Add(System.IO.Path.GetFileName(FileName));
Session["MyArrayList"] = idList;
}
protected void SendEmail(object sender, EventArgs e)
{
// To view the Arraylist
ArrayList idList = (ArrayList)Session["MyArrayList"];
foreach (string val in idList)
{
Response.Write(val);
}
}
First off use List<T> instead of ArrayList.
List<string> idList = new List<string>();
idList.Add(System.IO.Path.GetFileName(FileName));
Note: List<T> will provide type-safety, so if you try to add anything besides a string to the list, then you will get a compilation error.
Second, you only need to update the Session value when you first load the page, not on every post back, instead do this:
In Login.cs
public void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
Session["MyArrayList"] = null;
}
}
In Share.cs
public void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
ArrayList idList = new ArrayList();
idList.Add(System.IO.Path.GetFileName(FileName));
Session["MyArrayList"] = idList;
}
}
Since you need to actually add stuff to your list each time the page loads your problem is that you're instantiating a new ArrayList each time it loads. So stuff get overwritten instead of being added. Here's what you actually need to do
Login.cs
public void Page_Load(object sender, EventArgs e)
{
Session["MyArrayList"] = new ArrayList();
}
Share.cs
public void Page_Load(object sender, EventArgs e)
{
ArrayList idList = (ArrayList)Session["MyArrayList"];
idList.Add(System.IO.Path.GetFileName(FileName));
Session["MyArrayList"] = idList;
}
In the login page we instantiate the list and store it in the session. In the other page, we get the previously stored list from session and assign it to idList and casting it properly, then we add the new stuff to it and return it back to the session.
Note:
This will generate an exception if the session is empty or if it doesn't contain an ArrayList. So you'll probably need to put a checking mechanism in your code.
I have a page where a instructor inserts a student's id into a text box and then submits it. It should then come up with a list of all the students that have been added. But every time the submit button is pressed, the list gets cleared and only the last student added is displayed.
public Service1Client ws = new Service1Client();
public string adress;
public List<ServiceReference1.User> lu;
protected void Page_Load(object sender, EventArgs e)
{
if (lu==null)
lu= new List<ServiceReference1.User>();
}
protected void Button1_Click(object sender, EventArgs e)
{
ServiceReference1.User u= new ServiceReference1.User();
u = ws.ShowUser(int.Parse(TextBox2.Text));
if (!IsContained(u))
{
lu.Add(u);
TextBox1.Text += u.FirstName;
}
}
Is there a way to solve this? Or must I send the information to the page via a query string?
Each HTTP request gets a new instance of your page.
You should store the list in ViewState to persist across requests.