Trying to pass a string between C# classes - c#

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.

Related

GridView select - passing values to textboxes on another form

I have a GridView with the select button turned on.
<asp:CommandField ShowSelectButton="True" />
I want to pass the row values to TextBoxes that are on another page. So I am just working with on to test with the moment.
I am currently using the following code.
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
string Property_Name;
Property_Name = GridView1.SelectedRow.Cells[4].Text;
Session["Property_Name"] = Property_Name;
CreateSurvey CS = new CreateSurvey();
CS.PropDetails();
Response.Redirect("CreateSurvey.aspx");
This is my code from the second page (CreateSurvey.aspx)
public void PropDetails()
{
var Property_Name = Session["Property_Name"];
Create_PropName.Text = Property_Name.ToString();
}
The "CreateSurvey.aspx" page opens but the Create_PropName TextBox is empty.
Am I missing something?
try this
if you wan't to use session
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
string Property_Name;
Property_Name = GridView1.SelectedRow.Cells[4].Text;
Session["Property_Name"] = Property_Name;
//you don't need this as you already set session above
//CreateSurvey CS = new CreateSurvey();
//CS.PropDetails();
Response.Redirect("CreateSurvey.aspx");
}
while receiving you just need to call below code in page load
if(Session["Property_Name"] != null)
Create_PropName.Text = Session["Property_Name"].ToString();
if you want to use query string
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
Response.Redirect("CreateSurvey.aspx?PropName="+GridView1.SelectedRow.Cells[4].Text);
}
in second page load
if(Request.QueryString["Property_Name"] != null)
Create_PropName.Text = Request.QueryString["Property_Name"];

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

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

ArrayList Session 2.0 - Overwritten

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.

session,cookies in asp.net c#

i want to pass a string value from one page to another.Also i have some text boxes and the values entered in it needs to be passed to a new page.How do i do it?
I have a string S
String S = Editor1.Content.ToString();
i want to pass value in string S onto a new page i.e Default2.aspx how can i do this in ASP.net C#
You can achieve it using Session or by QueryString
By Session
In your first page:
String S = Editor1.Content.ToString();
Session["Editor"] = S;
Then in your next page access the session using:
protected void Page_Load(object sender, EventArgs e)
{
String editor = String.Empty;
if(!String.IsNullOrEmpty(Session["Editor"].ToString()))
{
editor = Session["Editor"].ToString();
// do Something();
}
else
{
// do Something();
}
}
-
By QueryString
In your first page:
// or other events
private void button1_Click(object sender, EventArgs e)
{
String S = Editor1.Content.ToString();
Response.Redirect("SecondPage.aspx?editor" + S)
}
In your second page:
protected void Page_Load(object sender, EventArgs e)
{
string editor = Request.QueryString["editor"].ToString();
// do Something();
}
Depends on what the value is. If it is just a parameter and is ok to be viewed by the user then it can be passed through QueryString.
e.g.
Response.Redirect("Default2.aspx?s=value")
And then accessed from the Default2 page like
string s = Request.QueryString["s"];
If it needs to be more secure then consider using session, but I wouldn't recommend using the Session excessively as it can have issues, especially if you are storing the session InProc which is ASP.NET default.
You can have a state server or database but, it might be better to have your own database based session based on the authenticated user, and have it cached in the website if need be.
Use Session["content"]=Editor1.Content.ToString() in page1...
in page2 use...string s = Session["content"]

Categories