ArrayList Session 2.0 - Overwritten - c#

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.

Related

how to maintain state for a table in asp.net

i am trying to upload a csv file data to DB.
the process is like :
i am extracting csv file data to DataTable.
validating DataTable fields .
if all good , loading them into DB on button click.
i am generating invTable at below validation method by passing saved csv file path on validate button click.
protected void ValidateData_Click(object sender, EventArgs e)
{
ValidateCsv();
}
private void ValidateCsv(string fileContent)
{
DataTable getCSVData;
getCSVData = GetData(fileContent);
invTable= Validate(getCSVData);
}
if am loading it on BulkUpload_Click, invTable is null.
ideally it should have data , as assinged in ValidateCsv method.
protected void BulkUpload_Click(object sender, EventArgs e)
{
MatchedRecords(invTable);
}
any idea how to maintain invTable data across postback?
Change your ValidateCsv to a function.
private DataTable ValidateCsv(string fileContent)
{
DataTable getCSVData;
getCSVData = GetData(fileContent);
invTable = Validate(getCSVData);
return invTable;
}
Then on your MatchedRecords, modify it to accept a DataTable parameter.
private void MatchedRecords(DataTable invTable) {
}
Then on your BulkUpload_Click event, reference to the ValidateCsv, now a function that returns the value of your DataTable to the MatchedRecords void.
protected void BulkUpload_Click(object sender, EventArgs e)
{
MatchedRecords(ValidateCsv('enter how you get the fileContent here...'));
}
Or
protected void BulkUpload_Click(object sender, EventArgs e)
{
DataTable valueTable = ValidateCsv('enter how you get the fileContent here...');
MatchedRecords(valueTable);
}

Trying to pass a string between C# classes

I'm trying to pass a string between C# classes by using a session. I have a class called Profile and it has a search box. I have another class called SearchResults that is supposed to search my database for whatever was entered in the search box.
Upon clicking on the search button, this method in the Profile class is called:
protected void Search(object sender, EventArgs e)
{
Response.Redirect("~/SearchResults.aspx");
String searchedItem = txt_search.Text;
Session["search"] = searchedItem;
}
and here is the Page_Load method in the SearchResults page:
protected void Page_Load(object sender, EventArgs e)
{
string searchedItem = (string)(Session["search"]);
string connStr = ConfigurationManager.ConnectionStrings["MyDbConn"].ToString();
SqlConnection conn = new SqlConnection(connStr);
SqlCommand SearchGames = new SqlCommand("SearchGames", conn);
SearchGames.CommandType = CommandType.StoredProcedure;
SearchGames.Parameters.Add(new SqlParameter("#game_name", searchedItem));
conn.Open();
SqlDataReader rdr = SearchGames.ExecuteReader(CommandBehavior.CloseConnection);
}
I'm getting an error saying that my
SearchGames procedure needs an #game_name parameter which wasn't
supplied
, however it's clear that I've passed that parameter, which leads me think that there's something wrong with SearchItem (or how I'm passing the string between the two classes.
You redirect before setting the session, I think you should redirect after setting session:
String searchedItem = txt_search.Text;
Session["search"] = searchedItem;
Response.Redirect("~/SearchResults.aspx");
Rather than trying to pass the parameter via the session, inject it into the redirect:
protected void Search(object sender, EventArgs e)
{
Response.Redirect($"~/SearchResults.aspx?search={txt_search.Text}");
}
or, if not using C# 6,
protected void Search(object sender, EventArgs e)
{
Response.Redirect("~/SearchResults.aspx?search=" + txt_search.Text);
}
Then within Page_Load, change it to:
protected void Page_Load(object sender, EventArgs e)
{
string searchedItem = Request.QueryString["search"];
...
That way, you avoid passing values through global variables, which will make the code more robust and make testing easier.

using C# solution for Listview label

I want to use this solution to convert URLs to link in a listview label.
private string ConvertUrlsToLinks(string text)
{
string regex = #"((www\.|(http|https|ftp|news|file)+\:\/\/)[_.a-z0-9-]+\.[a-z0-9\/_:#=.+?,##%&~_-]*[^.|\'|\# |!|\(|?|,| |>|<|;|\)])";
System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex(regex, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
return r.Replace(text, "$1").Replace("href=\"www", "href=\"http://www");
}
I have tried this in the listview databound but its not working.
protected void ProjectRecentActiviyListView_ItemDataBound(object sender, ListViewItemEventArgs e)
{
Label ProjectPostLabel = (Label)e.Item.FindControl("ProjectPostLabel");
ProjectPostLabel = ConvertUrlsToLinks({0});
}
Thank you
According to your code you are using ASP.NET Web Forms, not MVC.
You must use your ProjectPostLabel instance with Text property - no need to create a new label that is not assign to anywhere.
From your event you must retrieve Url property, not the label control. I have used NorthwindEmployee class with URL property in my ListView. You must cast it to your own class that is used in the list view.
protected void ProjectRecentActiviyListView_ItemDataBound(object sender, ListViewItemEventArgs e)
{
ProjectPostLabel.Text = ConvertUrlsToLinks(((NorthwindEmployee)e.Item.DataItem).URL);
}
And you must remember that only the last item from your list view will be displayed in the label (unless you expect that behavior). If you want to list of URLs from the list you can write this:
protected void Page_Load(object sender, EventArgs e)
{
ProjectPostLabel.Text = string.Empty;
}
protected void ProjectRecentActiviyListView_ItemDataBound(object sender, ListViewItemEventArgs e)
{
ProjectPostLabel.Text += string.Format("{0}<br/>", ConvertUrlsToLinks(((NorthwindEmployee)e.Item.DataItem).URL));
}

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

Trying to keep contents of checkbox List when returned to page

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

Categories