Why does my list reset when I press a button? - c#

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.

Related

How to reload combobox items in one form from another form

I have two window forms, Form1 is for country name and Form2 is for city name. In form2 I have a comboBox which fetch country name from database that I saved by Form1 and its working fine and fetching data properly. But I want a button beside comboBox like
please see this image for better understanding,
and when click on it button will open Form1 and when I will add a new country in Form1, comboBox in Form2 should get updated and Form1 should close. How to do this? My code is...
In Form2 (for city name)
private void addBtn_Click(object sender, EventArgs e)
{
Add_Country ac = new Add_Country();
ac.ShowDialog();
}
public void refreshComboBox()
{
comboBox_CountryName.Refresh();
}
In Form1(for country name)
private void saveBtn_Click(object sender, EventArgs e)
{
string country = txtBox_countryName.Text.ToLower();
insertCountry(country);
showCountry();
Add_City ad = new Add_City(); //Form2 object refrence.
ad.refreshComboBox();
this.Close();
MessageBox.Show("Country added successfully.");
clearControl();
}
The line ac.ShowDialog() helps you handle after the Add_Country form is closed. So, you can refetch the countries from database just after ShowDialog line such as;
private void addBtn_Click(object sender, EventArgs e)
{
Add_Country ac = new Add_Country();
ac.ShowDialog();
// Repopulate the Country Combobox
}
in form2 after showdialog() refresh your combo,
you don't need to refresh it in the first form
private void addBtn_Click(object sender, EventArgs e)
{
Add_Country ac = new Add_Country();
ac.ShowDialog();
refreshComboBox()
}
when you are closing the dialog the run time cursor will be back to the form2 and the other story will be executed

Why does my variable lose its value?

From the selectedindexchanged event, my variable has a value, but when it reaches the btn_click() event, the variable no longer has a value. Why is that?
public partial class TestingDatapass
{
private string item = null;
private string itemprice = null;
private int totalprice = 0;
protected void item_selectedindexchanged(object sender, EventArgs e)
{
//Both have a value here
item = item.SelectedValue;
itemprice = item.SelectedValue.Text;
}
protected void btn_click(object sender, EventArgs e)
{
//no value here
totalprice = Convert.ToInt32(itemprice)*Convert.ToInt32(item);
MessageBox.Show(totalprice);
}
}
EDIT
And to answer the ? posed in comments, the order of occurrence is the selectedindexchange THEN the btn_click()
EDIT REGARDING View State
So then would this be a proper way to set up what I am trying to achieve?
public partial class TestingDatapass
{
private int totalprice = 0;
protected void item_selectedindexchanged(object sender, EventArgs e)
{
ViewState["item"] = item.SelectedValue;
ViewState["itemprice"] = item.SelectedValue.Text;
}
protected void btn_click(object sender, EventArgs e)
{
totalprice = Convert.ToInt32(ViewState["item"])*Convert.ToInt32(ViewState["itemprice"]);
}
}
When a page is requested, ASP.NET creates an instance of TestingDatapass class and initialize itemprice,totalprice etc. fields. Now when you change your dropdown from client (which I assume looking at your item_selectedindexchanged method), Postback happens and it assign values you have mentioned in item_selectedindexchanged. Finally it destroys the instance, generates the html and sends it back to browser.
Now, when you press the button in your page then a new instance is created, your fields are re-initialized and you don't see the changed values in btn_click. This is how it works.
Thus if you want to preserve any data across postback, Consider using any State Management technique like ViewState, HiddenField etc.
Also, as a side note, MessageBox.Show is not available in ASP.NET.
Update:
I answered in the context of why it is not retaining the value in button click event, there are many ways to do it. But to answer your question, I don't see any reason to store the values in item_selectedindexchanged event as you are not doing anything there. You can directly access the dropdown selected values in button click handler like this:-
protected void btn_click(object sender, EventArgs e)
{
totalprice = Convert.ToInt32(item.SelectedValue) *
Convert.ToInt32(item.SelectedItem.Text);
}
Also, please note it's item.SelectedItem.Text and not SelectedValue.Text.

Asp.net c# : ListBox showing only one item

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;
}
}

Same webpage always loads with webBrowser

I have a program that I wrote for sending messages to some of my friends through a website. It works fine, but for some reason I can't get it to work correctly with just one button click event. If I don't have a second button click for the SEND data method (whichs POSTs the data), it will always just keep sending the message to the same person, eventhough the new URL is loaded into the webBrowser URL*, but if I have that second click event all works fine. What am I missing?
*Using the debugger I see a new URL load with every iteration, but I do see on the HTTP debugger that the program is sending to the same URL each time
private void button1_Click(object sender, EventArgs e)
{
ListBox();
}
private void ListBox()
{
//gets name from ListBox
GetData();
}
private void GetData()
{
webBrowser1.Navigate(inputURLID);
//SendData (); Always sends to the same person if I call from here, so I made a second button click and it works fine
}
private void button2_Click(object sender, EventArgs e)// works fine like this
{
webBrowser1.Document.GetElementById("subject").SetAttribute("value", textBox2.Text);//To (username)
webBrowser1.Document.GetElementById("message").SetAttribute("value", richTextBox1.Text);//Subject
webBrowser1.Document.GetElementById("Submit").InvokeMember("click");//Message
}
....
private void SendData()// always sends to the same person if I just do it like this
{
webBrowser1.Document.GetElementById("subject").SetAttribute("value", textBox2.Text);//To (username)
webBrowser1.Document.GetElementById("message").SetAttribute("value", richTextBox1.Text);//Subject
webBrowser1.Document.GetElementById("Submit").InvokeMember("click");//Message
}
Try to populate your fields only when the url has been loaded (when DocumentCompleted event is fired):
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
webBrowser1.Document.GetElementById("subject").SetAttribute("value", textBox2.Text);//To (username)
webBrowser1.Document.GetElementById("message").SetAttribute("value", richTextBox1.Text);//Subject
webBrowser1.Document.GetElementById("Submit").InvokeMember("click");//Message
}

Add textbox text to new string in list each time button is pressed

This is the code:
private void button1_Click(object sender, EventArgs e)
{
List<string> user = new List<string>();
user.Add(usertextBox.Text);
I want it where each time I press the button, whatever is in usertextBox at that point gets added to the list 'user' as a new item, so I can recall the different ones later with [1], [2], [3], etc. I also want it so the user can close the app and all the users will still be saved. I I don't know if C# does this automatically
Even if you can only answer one of my questions that's fine. Thanks!!
In your code you are making List local to Button that means every time you click button new object of List is created, You should create it out side button click method. Try this.
List<string> user = new List<string>();
private void button1_Click(object sender, EventArgs e)
{
user.Add(usertextBox.Text);
You have to define the List out side of the method. C# does not keep the content of the list.
private List<string> user = new List<string>();
private void button1_Click(object sender, EventArgs e)
{
user.Add(usertextBox.Text);
}
for saving the content you could use a database (http://msdn.microsoft.com/en-us/library/bb655884%28v=vs.90%29.aspx) or an xml file (http://www.codeproject.com/Articles/7718/Using-XML-in-C-in-the-simplest-way).
to save the content of the List you could create a new class containing this two methods instead of the list
public List<string> getListContent()
{
//read xml-file
}
public void Add(string t)
{
//write to xml file
}
This will just fine work in single thread applications.

Categories