Accessing previous value in Hashtable during page refresh - c#

I have a hyperlink field in a gridview. I want to store all the clicked value during a session in a hashtable for that hyperlink field.
protected partial class User : System.Web.UI.Page
{
Hashtable htable = new Hashtable();
int hTableIndex = 0;
// ...
}
In Page Load Function.
if(Session["test"] != null)`
{
for(int i = 0 ; i gvUserStatus.Rows.Count ; i++)
Hashtable tempHashTable = new Hashtable();
tempHashTable = Session["test"] as Hashtable;
if(tempHashTable.Contains(someValue))
{
//Do Something
}
}
In link click event:
protected void userID_Click(object sender, EventArgs e)
{
//logic to get the ClickedValue
if(!htable.Contains(ClickedValue))
{
htable.Add(hTableIndex++,ClickedValue);
}
Session["test"] = htable;
}
I am using the above code, but in my hash table, only the last clicked value is getting stored, what should I do to get all the previous value for an entire user session?

hTableIndex will lose its value upon postback. You will need to store it in Session as well (or just ViewState if you won't need it's value on other pages)
So you need to add this in your Page_Load event:
if (ViewState["hTableIndex"] == null)
ViewState["hTableIndex"] = hTableIndex;
and in your link click event userID_Click
protected void userID_Click(object sender, EventArgs e)
{
//logic to get the ClickedValue
if(!htable.Contains(ClickedValue))
{
var hTableIndex = Convert.ToInt32(ViewState["hTableIndex"]);
htable.Add(hTableIndex++,ClickedValue);
}
Session["test"] = htable;
}
Let me know if this works. Haven't tested it yet.

The problem is within your hTableIndex which will always point to 0 on reloading the page, you also need to put it in the session, so that next time you can get the max value of hTableIndex and add the new link at that index

Related

Data Pager Postback causes value lose

I am new to asp.net. Here is the scenario. I am trying to build a Search functionality. If I enter the value in search box i.e. "Test" and click search icon SQL Server returns results. I have limited datapage size = "1". When I click on next page it refreshes the page and my search box looses the value I entered in this case "Test". If no value is passed SQL Server returns a default result so everytime I navigate through pages it works only for first page each click after that returns me default value. I bind list view on PreRender of datapage. Here are the code snippets.
protected void search_ServerClick(object sender, EventArgs e)
{
mydatapager_PreRender(sender, e);
}
protected void mydatapager_PreRender(object sender, EventArgs e)
{
string var_search_firstname = globalsearchinput.Value.ToString();
string var_search_city = citysearchinput.Value.ToString();
string var_search_state = statesearchinput.Value.ToString();
bool isadvancedsearch = false;
//Determine whether it's advanced search or not.
string MethodCaller = "";
//MethodCaller = ((HtmlButton)sender).ID;
//if (MethodCaller == "search")
//{
// isadvancedsearch = false;
//}
//else
//{
// isadvancedsearch = true;
//}
Utility utl = new Utility();
friendrequestsentnotificationpanel.Visible = false;
listview1.DataSource = utl.SearchProfile(var_search_firstname, var_search_city, var_search_state, isadvancedsearch);
listview1.DataBind();
}
Add ispostback==false condition in preRender. It helps to retain the serch string

Dropdown list binding issue in asp.net

I have a placeholder which has some dropdownlist and a button, now this placeholder is initially hidden and when user makes any search on the page, based on that the placeholder gets visible and the dropdownlist gets filled, this is working absolutely fineNow the problem starts when i click on the button inside the placeholder (next to dropdownlist), at this point of time, all the dropdownlist gets blank. I understand first page load executes and because there are no bindings (as dropdowns are binded on search click) it would make it blank, but i am not getting once the dropdown has been binded why it would matter for the page load to unbind it. Here's my code:
Page Load:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
plcView.Visible = false;
}
}
Search Button Click:
protected void btnSearch_Click(object sender, EventArgs e)
{
try
{
if (!AppGlobal.IsSanadCompleted(AppGlobal.Sanads.Amma, txtITSId.Text))
{
lblErrorMessage.CssClass = "dnnFormMessage dnnFormWarning";
lblErrorMessage.Text = "You need Amma Sanad to attempt for Hifz Program.";
plcView.Visible = false;
}
else
{
plcView.Visible = true;
txtJuz.Text = (Hifz.GetLastJuzAttempted(txtITSId.Text) + 1).ToString();
drpAyahFrom.DataTextField = "Key";
drpAyahFrom.DataValueField = "Value";
drpAyahFrom.DataSource = objHifz.GetAyahListForHifzProgram(Convert.ToInt32(txtJuz.Text));
drpAyahFrom.DataBind();
drpAyahTo.DataTextField = "Key";
drpAyahTo.DataValueField = "Value";
drpAyahTo.DataSource = objHifz.GetAyahListForHifzProgram(Convert.ToInt32(txtJuz.Text));
drpAyahTo.DataBind();
drpGrade.DataSource = AppGlobal.GetGrades();
drpGrade.DataBind();
}
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
}
I even tried enabling EnableViewstate at page and also at skin (I am using Dotnetnuke) level, but still it does not makes any difference.
Can anyone please suggest where i would be getting wrong.
DotNetNuke is nothing but an ASP.Net app. So to look into your issue we have to delve into the Page Life-Cycle of an ASP.Net page. There you will notice a Page_Event called SaveStateComplete. You see, this is called just before the Render event(At this event the page is displayed to the end user). So any changes done after rendering the page will not be saved in to the ViewState by default. Since your DropDowns are blank during SaveStateComplete, after a PostBack you're getting empty DropDowns.
The solution is to forcefully save the DataSource in your custom ViewState. For ex. in your button click, add the following:
var obj = objHifz.GetAyahListForHifzProgram(Convert.ToInt32(txtJuz.Text)));
drpAyahFrom.DataSource = obj;
ViewState["myUniqueKey"] = obj;
Then at the Page_Load event, you can use:
if (!IsPostBack)
{
plcView.Visible = false;
}
else
{
if(ViewState["myUniqueKey"] != null)
{
drpAyahFrom.DataTextField = "Key";
drpAyahFrom.DataValueField = "Value";
drpAyahFrom.DataSource = ViewState["myUniqueKey"];
drpAyahFrom.DataBind();
}
}
You may have to perform the casting as per the requirement.

Store Selected Values From Drop Down List in Session Variables

I am trying to store the selected value of an item in my drop down list into a session variable after selecting it and pressing a button to add it to a session variable. My question is, is there a way to store multiple selections into different session variable with the same drop down list. Each session variable has the same value and I am unsure how to save each selected value into a new session variable.
protected void DropDownListAddNumber_SelectedIndexChanged(object sender, EventArgs e)
{
Session["selectionOne"] = DropDownListAddNumber.Items.FindByValue(DropDownListAddNumber.SelectedValue);
Session["selectionTwo"] = DropDownListAddNumber.Items.FindByValue(DropDownListAddNumber.SelectedValue);
Session["selectionThree"] = DropDownListAddNumber.Items.FindByValue(DropDownListAddNumber.SelectedValue);
Session["selectionFour"] = DropDownListAddNumber.Items.FindByValue(DropDownListAddNumber.SelectedValue);
}
If multi-select is not your question, storing it by each variable will not scale well. If you want to store each selection into the Session, you can store a List of strings into the session. (taking advantage of the fact that the items are stored in the order we insert them in a list)
protected void DropDownListAddNumber_SelectedIndexChanged(object sender, EventArgs e)
{
List<string> sessionList = GetSessionVariable();
sessionList.Add(DropDownListAddNumber.Items.FindByValue
(DropDownListAddNumber.SelectedValue));
}
// you can access the selected values from the list
// if sessionList.Any(), then sessionList.Last() will contain
// the last selected value.. etc.
private List<string> GetSessionVariable()
{
var list = Session["SelectionValuesList"] as List<string>;
if (list == null)
{
list = new List<string>();
Session["SelectionValuesList"] = list;
}
return list;
}
OR
if you still want to use multiple session variables, you need to do some sort of counter.
multiple variables will be created. this is error prone.
int lastCounter = 0;
protected void DropDownListAddNumber_SelectedIndexChanged(object sender, EventArgs e)
{
++lastCounter;
Session["selection" + lastCounter] = DropDownListAddNumber.Items
.FindByValue(DropDownListAddNumber.SelectedValue);
}
// you can access last value as
// var lastSelectedValue = Session["selection" + lastCounter];

Text field default value overrides user input

I'm setting some default value for my text fields and those fields are in read only mode. When I pass new values to the those fields and submits the form it saved default value not the new one. I have used PostBack function but it's not working. Here is my code,
protected void Page_Load(object sender, EventArgs e)
{
if (! this.IsPostBack)
{
MakeReadControl();
}
}
private void MakeReadControl()
{
((TextBox)this.FindControl("txtMedicalCheckup")).Text = System.DateTime.Now.ToShortDateString();
((TextBox)this.FindControl("txtBosiet")).Text = System.DateTime.Now.ToShortDateString();
((TextBox)this.FindControl("txtLandSurvival")).Text = System.DateTime.Now.ToShortDateString();
((TextBox)this.FindControl("txtDefensiveDriving")).Text = System.DateTime.Now.ToShortDateString();
((DropDownList)this.FindControl("comboDrivingLicense")).SelectedIndex = 1;
((TextBox)this.FindControl("txtOtherLicense")).Text = "Not available";
}
However, the drop down list updates the value correctly.
Update:-
Instead of Read Only attribute if I use enable attribute then it works fine.

How do I pass variable between .aspx pages after clicking [OK] in a C# web form

I'm new to web forms.
1) My default web form is Default.aspx. It has a couple of combo boxes, and a Button control: all ASP.Net web controls.
2) In the Page_load(), I create a C# object "ScoringInfo ()":
protected void Page_Load(object sender, EventArgs e)
{
scoringInfo = new ScoringInfo();
...
3) ScoringInfo reads some info from a database into member variables, and uses the member variables to fill the combo boxes:
scoringInfo.GetOpenCrossByDate(dt, openCrossInfo);
cbAvailableBowlers.Items.Clear ();
foreach (OpenCrossInfoRec rec in openCrossInfo)
string s =
String.Format(
"Lane {0:00}: {1}",
rec.laneNo, rec.dateTime);
cbAvailableBowlers.Items.Add(s);
...
4) Here are the member variables:
...
protected ScoringInfo scoringInfo;
protected List leagueInfo = new List();
protected List openCrossInfo = new List();
5) When the user presses the button, I want to display a second .aspx page which processes the specific combo box item the user selected. Here is my "OnClick" event handler:
protected void bTest_Click1(object sender, EventArgs e)
{
int idx = cbAvailableBowlers.SelectedIndex;
Session["openCrossLaneUniqueId"] = openCrossInfo[idx].laneUniqueId;
...// THIS FAILS:
// "ARGUMENT OUT OF RANGE" exception;
// "idx" is 0; openCrossInfo[] list is empty...
It doesn't work ... because member variable, "openCrossInfo[]" and combo box property SelectedIndex don't seem to be valid any longer when bTest_Click1 is executed!
How/where do I save the state of the UI for other, subsequent pages in the same session?
The member variables for the page (such as openCrossInfo) will not persist from request to request. The Page object for the .aspx is created again each time a new request comes in. So when the event for bTest_Click fires, it is working with a new copy of the Page object. Your openCrossInfo array has no values because the page object was just freshly created, even though you set it in an earlier request.
If you want save state you will have to use something else such as Session state.
The problem, as Jay Douglass pointed out, is that the member variable "openCrossInfo" from the original page isn't persisted to the new, "postback" page.
The solution was:
create and initialize the objects in the original page ("if !IsPostBack"), save the initialized objects to the Session, then
restore them from the Session for the subsequent page:
protected void Page_Load(object sender, EventArgs e)
{
scoringInfo = new ScoringInfo();
if (!IsPostBack)
{
// 1st time, use current date/time; create new data
leagueInfo = new List<LeagueInfoRec>();
openCrossInfo = new List<OpenCrossInfoRec>();
laneUniqueIds = new List<string>();
updateGui(DateTime.Now);
Session["leagueInfo"] = leagueInfo;
Session["openCrossInfo"] = openCrossInfo;
Session["laneUniqueIds"] = laneUniqueIds;
}
else
{
// Subsequent callbacks: retrieve state
leagueInfo = (List<LeagueInfoRec>)Session["leagueInfo"];
openCrossInfo = (List<OpenCrossInfoRec>)Session["openCrossInfo"];
laneUniqueIds = (List<string>)Session["laneUniqueIds"];
}
}

Categories