Session variable at master page is null in ASP.NET - c#

In my login page code behind:
After success of DB
protected void btnLogin_Click(object sender, EventArgs e)
{
int intErr = 0;
LoginDetails objLogDetails = new LoginDetails();
objLogDetails.UserName = txtUsername.Value.ToString();
objLogDetails.UserPassword = txtUserpassword.Value.ToString();
if (Request.Form["rdoLogType"] != null)
sType = Request.Form["rdoLogType"].ToString();
else if (Request.Form["rdoLogType"] == null && txtUsername.Value.ToString().ToLower() == "admin")
sType = "3";
else
sType = "0";
try
{
if (Request.Form["rdoLogType"] == null)
{
intErr = 1;
divErrMsg.InnerText = "Please Select Login type.";
divErrMsg.Visible = true;
}
else
{
int intLogId = 0;
ServeAtDoorstepService objService = new ServeAtDoorstepService();
if (sType == "1")
intLogId = objService.LoginCustomer(objLogDetails);
if (sType == "2")
intLogId = objService.LoginVendor(objLogDetails);
if (sType == "3")
intLogId = objService.LoginCustomer(objLogDetails);
if (string.IsNullOrEmpty(intLogId.ToString().Trim()))
{
intErr = 1;
divErrMsg.InnerText = "Invalid Loginname and Password! Please try again.";
divErrMsg.Visible = true;
}
else
{
Session.Abandon();
Session.RemoveAll();
Session.Add("LoginId", intLogId.ToString());
Session.Add("LoginType", sType);
if (chkAgree.Checked == true)
{
HttpCookie cLoginId = new HttpCookie("LoginId", intLogId.ToString().Trim());
HttpCookie cLoginType = new HttpCookie("LoginType", sType);
cLoginId.Expires = DateTime.Now.AddDays(5);
cLoginType.Expires = DateTime.Now.AddDays(5);
Response.Cookies.Add(cLoginId);
Response.Cookies.Add(cLoginType);
HttpCookie cLoginName = new HttpCookie("LoginName", txtUsername.Value.ToString().Trim());
HttpCookie cPassword = new HttpCookie("Password", txtUserpassword.Value.ToString().Trim());
cLoginName.Expires = DateTime.Now.AddDays(5);
cPassword.Expires = DateTime.Now.AddDays(5);
Response.Cookies.Add(cLoginName);
Response.Cookies.Add(cPassword);
}
}
}
}
catch (System.Threading.ThreadAbortException)
{
}
catch (Exception ex)
{
divErrMsg.InnerText = ex.Message.ToString();
intErr = 1;
}
if (intErr == 0 && Session["LoginType"].ToString() == "1")
Response.Redirect("MyCustomerDash.aspx");
else if (intErr == 0 && Session["LoginType"].ToString() == "2")
Response.Redirect("MyVendorDash.aspx");
else if (intErr == 0 && Session["LoginType"].ToString() == "3")
Response.Redirect("MyAdminDash.aspx");
}
At my master page
this master page is common to all page
protected void Page_Load(object sender, EventArgs e)
{
isShowHideControl = "0";
lblWelcomeMsg.Visible = false;
lblDashboard.Visible = false;
if (Session["LoginId"] != null && (Session["LoginType"] != null && Session["LoginType"].ToString() == "3"))
{
lblWelcomeMsg.Visible = true;
lblDashboard.Visible = true;
isShowHideControl = "3"; // Admin
}
else if (Session["LoginId"] != null && (Session["LoginType"] != null && Session["LoginType"].ToString() == "2"))
{
lblWelcomeMsg.Visible = true;
lblDashboard.Visible = true;
isShowHideControl = "2"; // Vendor
}
else if (Session["LoginId"] != null && (Session["LoginType"] != null && Session["LoginType"].ToString() == "1"))
{
lblWelcomeMsg.Visible = true;
lblDashboard.Visible = true;
isShowHideControl = "1"; // Customer
}
}
But LoginId AND LoginType are always null.
Please help me to get the session value.

This is most likely due to the event life cycle of master pages/web forms. I'm not entirely certain, but the mast page Load event may be firing after your Click event. See this page for details: http://msdn.microsoft.com/en-us/library/dct97kc3.ASPX

See msdn Session.Abandon
When the Abandon method is called, the current Session object is queued for deletion but is not actually deleted until all of the script commands on the current page have been processed. This means that you can access variables stored in the Session object on the same page as the call to the Abandon method but not in any subsequent Web pages.
For example, in the following script, the third line prints the value Mary. This is because the Session object is not destroyed until the server has finished processing the script.
<%
Session.Abandon
Session("MyName") = "Mary"
Reponse.Write(Session("MyName"))
%>
so in your sample you abandon session before redirect and on other pages it becomes unavailable. So for resolve try delete this line from your code in login page
Session.Abandon();

Related

My function is not called after a postback in asp.net webforms

I have a function called SetActionSection() which i placed in my pageload. I'm expecting it to be called but nothing happens. I get the result I want when I reload the page.
Here's the my pageload
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string fullName = GetUserFullName();
string id = Request.QueryString["id"];
TextBoxProjectManager.Text = fullName;
if (id != null)
{
GetCMMDetails(TextBoxProjectManager.Text);
int valid = ValidateUserAccess(id, fullName);
if (valid > 0)
GetProjectPostEval();
else
{
Response.Write("You are not allowed to access this data.");
ActionSection.Visible = false;
}
}
else
{
TextBoxProjectManager.Text = fullName;
GetCMMDetails(fullName);
}
SetActionSection();
}
}
Here is SetActionSection() function which shows the a button based on the status in the database.
private void SetActionSection()
{
string id = Request.QueryString["id"];
if (id == null)
{
LinkButtonSaveDraft.Visible = true;
LinkButtonSubmit.Visible = true;
ActionSection.Visible = true;
return;
}
string status = GetStatus(id);
string projectManager = GetCMM(id, "ProjectManager");
string buco = GetCMM(id, "Buco");
string businessExecutiveOfficer = GetCMM(id, "BusinessExecutiveOfficer");
string i2lFunctionLead = GetCMM(id, "I2LFunctionLead");
string user = GetUserFullName();
if ((status.Equals("Draft", StringComparison.OrdinalIgnoreCase))
&& user.Equals(projectManager, StringComparison.OrdinalIgnoreCase))
{
Response.Write(status + " Draft");
LinkButtonSaveDraft.Visible = true;
LinkButtonSubmit.Visible = true;
ActionSection.Visible = true;
}
if (status.Equals("Submitted", StringComparison.OrdinalIgnoreCase) &&
user.Equals(buco))
{
Response.Write(status + " Submitted");
LinkButtonSaveDraft.Visible = false;
LinkButtonSubmit.Visible = false;
LinkButtonBUCOApprove.Visible = true;
ActionSection.Visible = true;
}
if (status.Equals("(Approved) - BUCO", StringComparison.OrdinalIgnoreCase) &&
user.Equals(businessExecutiveOfficer))
{
Response.Write(status + " (Approved) - BUCO");
LinkButtonBUCOApprove.Visible = false;
LinkButtonBEOApprove.Visible = true;
}
if (status.Equals("(Approved) - BEO", StringComparison.OrdinalIgnoreCase) &&
user.Equals(businessExecutiveOfficer))
{
Response.Write(status + " (Approved) - BEO");
LinkButtonBEOApprove.Visible = false;
LinkButtonI2LFunctionLeadApprove.Visible = true;
}
if (status.Equals("(Approved) - I2L Function Lead", StringComparison.OrdinalIgnoreCase))
{
Response.Write(status + " (Approved) - I2L Function Lead");
LinkButtonI2LFunctionLeadApprove.Visible = false;
}
}
I have tested the SetActionSection method and it works. I just want it to be called when the user clicks the submit button. By the way. I'm redirecting to the same form.
Anything inside your if(!IsPostBack) condition will only be executed on initial load and not on submit. You could put the code you want to run on submit (postback) inside an else if you want
if (!IsPostBack)
{
....
}
else
{
SetActionSection();
}
https://learn.microsoft.com/en-us/dotnet/api/system.web.ui.page.ispostback?view=netframework-4.8
Or put your code inside a button click event

Unable to check all check boxes in a GridView

I am using grid view check box to select all the values in the grid view when i click the check box, but the problem i am facing is it is selecting the only the first page value how ever i have coded to bring all the values in but in design it is not working out
this is the image
i want all the check box to checked in design when i press the all check button.
protected void gvBatch_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
if (e.Row.RowType != DataControlRowType.Header && e.Row.RowType != DataControlRowType.Footer && e.Row.RowType != DataControlRowType.Pager)
{
DropDownList ddlcountry1 = (DropDownList)e.Row.FindControl("ddlcountry");
populateLocationValues(ddlcountry1);
{
ArrayList checkboxvalues = (ArrayList)Session["BP_PrdId"];
//string Bp_Id = "";
if (checkboxvalues != null && checkboxvalues.Count > 0)
{
string strBp_Id = ((HiddenField)e.Row.FindControl("hf_ProductLblId")).Value.ToString();
if (checkboxvalues.Contains(strBp_Id))
{
CheckBox myCheckBox = (CheckBox)e.Row.FindControl("chkPLPSltItem");
myCheckBox.Checked = true;
}
}
}
DataSet dsaccess = MenuRestriction();
DataRow dr = null;
string sView = "";
string sEdit = "";
string sInsert = "";
string sDeactive = "";
if (dsaccess.Tables.Count > 0)
{
if (dsaccess.Tables[0].Rows.Count > 0)
{
dr = dsaccess.Tables[0].Rows[0];
sView = dr["MnuRgts_View"].ToString();
sEdit = dr["MnuRgts_Edit"].ToString();
sInsert = dr["MnuRgts_Insert"].ToString();
sDeactive = dr["MnuRgts_DeActivate"].ToString();
if (sInsert == "Y" && sDeactive == "Y")
{
BtnDelete.Visible = true;
imgNew.Visible = true;
}
else
{
BtnDelete.Visible = false;
imgNew.Visible = false;
if (sInsert == "Y")
{
imgNew.Visible = true;
}
if (sDeactive == "Y")
{
BtnDelete.Visible = true;
}
}
}
}
}
}
catch (Exception ex)
{
log.Error("gvBatch_RowDataBound", ex);
}
}
protected void gvBatch_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
try
{
RememberOldValues();
gvBatch.PageIndex = e.NewPageIndex;
//RetrieveValues();
BindGrid();
LoadLocation();
//RePopulateValues();
}
private void RememberOldValues()
{
ArrayList checkboxvalues = new ArrayList();
string strBp_Id = "";
foreach (GridViewRow row in gvBatch.Rows)
{
//index = (int)gvBatch.DataKeys[row.RowIndex].Value;
strBp_Id = ((HiddenField)row.FindControl("hf_ProductLblId")).Value.ToString();
bool result = ((CheckBox)row.FindControl("chkPLPSltItem")).Checked;
// Check in the Session
if (Session["BP_PrdId"] != null)
checkboxvalues = (ArrayList)Session["BP_PrdId"];
if (result)
{
if (!checkboxvalues.Contains(strBp_Id))
checkboxvalues.Add(strBp_Id);
}
else
{
if (checkboxvalues.Contains(strBp_Id))
checkboxvalues.Remove(strBp_Id);
}
}
if (checkboxvalues != null && checkboxvalues.Count > 0)
Session["BP_PrdId"] = checkboxvalues;
}
protected void gvBatch_PreRender(object sender, EventArgs e)
{
try
{
if (gvBatch.TopPagerRow != null)
{
((Label)gvBatch.TopPagerRow.FindControl("lbCurrentPage")).Text = (gvBatch.PageIndex + 1).ToString();
((Label)gvBatch.TopPagerRow.FindControl("lbTotalPages")).Text = gvBatch.PageCount.ToString();
((LinkButton)gvBatch.TopPagerRow.FindControl("lbtnFirst")).Visible = gvBatch.PageIndex != 0;
((LinkButton)gvBatch.TopPagerRow.FindControl("lbtnPrev")).Visible = gvBatch.PageIndex != 0;
((LinkButton)gvBatch.TopPagerRow.FindControl("lbtnNext")).Visible = gvBatch.PageCount != (gvBatch.PageIndex + 1);
((LinkButton)gvBatch.TopPagerRow.FindControl("lbtnLast")).Visible = gvBatch.PageCount != (gvBatch.PageIndex + 1);
DropDownList ddlist = (DropDownList)gvBatch.TopPagerRow.FindControl("ddlPageItems");
ddlist.SelectedIndex = ddlist.Items.IndexOf(ddlist.Items.FindByValue(ViewState["DropDownPageItems"].ToString()));
gvBatch.AllowPaging = true;
gvBatch.TopPagerRow.Visible = true;
}
}
catch (Exception ex)
{
}
}
protected void gvBatch_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
if (e.CommandName == "EDIT")
{
GridViewRow row = (GridViewRow)((Control)e.CommandSource).Parent.Parent;
string strAgentName = ((HiddenField)row.FindControl("hf_loginName")).Value.ToString();
if (strAgentName != "")
{
Response.Redirect("CustomerDetails.aspx?Name=" + strAgentName, false);
}
}
}
catch (Exception ex)
{
log.Error("gvAgentRowcommand_AgentSummary", ex);
}
}
You can keep a boolean field in your code and set its value to true whenever the select all is clicked. When loading new pages, you can check that field to automatically display all checked. The same can be done when exporting the grid also.
you can modify and use the following Method
private void selectAllChecksInDAtaGrid()
{
foreach (DataGridViewRow item in myDataGrid.Rows)
{
if (Convert.ToBoolean(item.Cells["Column_Name"].Value) == false)
{
item.Cells["Column_Name"].Value = true;
}
}
}
the 'Column_name' is the name of the checkbox column. if you haven'nt named it yet you can also use the index number .
in your case its 0
private void selectAllChecksInDAtaGrid()
{
foreach (DataGridViewRow item in myDataGrid.Rows)
{
if (Convert.ToBoolean(item.Cells[0].Value) == false)
{
item.Cells[0].Value = true;
}
}
}
You should update (ArrayList)Session["BP_PrdId"] to include all the "Id"s of datasource of gridview. then bind data again.

Why i can not add data into new added column

I am amateur C# developer.Now i'm working on destkop application and work with MS2015 and SQL Management Studio.I have added new column into my database and write what is needed for it in .cs code,but can not add my data into column.It always shows NULL even if it is not empty.Here is my code about saving data:
private void btnSave_Click(object sender, EventArgs e) {
if (txtAmount.Text=="" ||txtBarcode.Text == "" || txtName.Text == "" || txtEntrance.Text == "" || txtExit.Text == "" || txtQuantity.Text == "" || txtStatus.Text == "")
{
SoundPlayer sp = new SoundPlayer(#"C:\Users\Nicat\Downloads\CompError.wav");
sp.Play();
MessageBox.Show("Please fill all gaps!");
}
else
{
model.Amount = txtAmount.Text.Trim();
model.Name = txtName.Text.Trim();
model.Entrance_Time = txtEntrance.Text.Trim();
model.Exit_Time = txtExit.Text.Trim();
model.Status = txtStatus.Text.Trim();
model.Quantity = txtQuantity.Text.Trim();
model.Barcode_No = txtBarcode.Text.Trim();
using (DBEntities db = new DBEntities())
{
if (model.ID == 0)
db.Tables.Add(model);
else
db.Entry(model).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();
}
Reset();
PopulateDataGridView();
SoundPlayer sp = new SoundPlayer(#"C:\Users\Nicat\Downloads\Button.wav");
sp.Play();
MessageBox.Show("Inventory submitted succesfully!");
}
}
If you add an exception handler, it will tell you what's wrong.
Wrap your code in a try/catch block.
try
{
// your code goes here
}
catch(Exception ex)
{
Debug.Writeln(ex.Message);
}

Handle PageIndexChanging event

I have a Query that runs when the user submits a search and the gridview is loaded.
I want to page the gridview and would usually have my grid in a LoadGrid(). I have the paging working ok and everything is good until I want to view page 2 of the GridView.
protected void btn_Search_Click(object sender, EventArgs e)
{
// Init()
// -----
pnl_Message.Visible = false;
lbl_message.Text = String.Empty;
// Clear grid of previous results
// ==============================
ResultsGridView.DataSource = null;
ResultsGridView.DataBind();
try
{
using (var db = new dbDataContext())
{
// Check Fields
// ------------
if (txt_CustomerName.Text == string.Empty && txt_CCNo.Text == string.Empty &&
txt_SwiftNo.Text == string.Empty && drp_Provider.SelectedValue == string.Empty)
{
lbl_message.Text += "* Please enter a search term";
pnl_Message.Visible = true;
pnl_Message.CssClass = "loginError";
pnl_results.Visible = false;
}
// Search Database
// ---------------
if (lbl_message.Text == String.Empty)
{
var customer = txt_CustomerName.Text.Length > 1 ? txt_CustomerName.Text.Trim() :
"Xcxcx";
//var provider = drp_Provider.SelectedItem.Text.Trim();
var concern = txt_CCNo.Text == "" ? 0 : Convert.ToInt32(txt_CCNo.Text);
var swiftid = txt_SwiftNo.Text == "" ? 0 : Convert.ToInt32(txt_SwiftNo.Text);
// Check which fields populated
// ----------------------------
var result =
from c in db.tbl_Concerns
where (c.ProviderId == Convert.ToInt32(drp_Provider.SelectedValue))
|| (c.person_Fullname.Contains(customer))
|| (c.SwiftId == swiftid)
|| (c.ConcernId == concern)
select new
{
c.ConcernId,
Swift = c.SwiftId,
FullName = c.person_Fullname,
Provider = c.tbl_Provider.provider_Name,
Concern_Detail = c.tbl_RaisedConcern.RaisedConcernText,
DateFrom = c.concern_DateFrom,
DateTo = c.concern_DateTo
};
// If No Results
// -------------
if (!result.Any())
{
lbl_message.Text += "* No results match your search, please try again.";
pnl_Message.Visible = true;
pnl_Message.CssClass = "loginError";
}
else
{
// Show Table
// ----------
pnl_results.Visible = true;
ResultsGridView.DataSource = result;
ResultsGridView.DataBind();
// Table Header Names
// ------------------
ResultsGridView.HeaderRow.Cells[0].Text = "Select";
}
}
}
}
catch (SystemException ex)
{
var exceptionUtility = new genericExceptions();
exceptionUtility.genericSystemException(
ex,
Server.MachineName,
Page.TemplateSourceDirectory.Remove(0, 1) + Page.AppRelativeVirtualPath.Remove(0, 1),
ConfigurationManager.AppSettings["emailSupport"],
ConfigurationManager.AppSettings["emailFrom"],
string.Empty);
}
}
My PageIndexChanging event I would usually call the loadGrid() but I do not have that situation. I have tried just adding ResultsGridView.DataBind() but get the error Sequence contains no elements.
protected void ResultsGridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
ResultsGridView.PageIndex = e.NewPageIndex;
** How Can I bind the Grid**
}
Try this..
session["somename"]=result;
protected void ResultsGridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
var somename=session["somename"].Tostring();
ResultsGridView.PageIndex = e.NewPageIndex;
ResultsGridview.Datasource=somename;
REsultsGridview.Databind();
}

Chrome/Safari Back button issue

I am making an application in which we may have 5 or 6 steps.
In first step, i will select the report which i need and save&continue..it will get me to second step...like so...
my problem is according to functionality, when i hit on the browser back button i need to go to previous page.
and again when i press it second time it has to go to my home page,
but it is redirecting me to the previous page.
It is working in all browsers except in chrome and safari.
I am inserting my code for reference..please help me to solve this..
protected void Page_Load(object sender, EventArgs e)
{
DisableHistory();
lnkBackBrowse.Style["visibility"] = "hidden";
if (Session["UserId"] != null)
{
if (Convert.ToInt32(Session["UserId"].ToString()) == 0)
{
TopNavigationMenu.Style["visibility"] = "hidden";
NavigationMenu.Style["visibility"] = "hidden";
if (!Request.Url.ToString().Contains("Home") && !Request.Url.ToString().Contains("SaveandLogout"))
Response.Redirect("Home.aspx");
}
else
{
TopNavigationMenu.Items[0].Text = "Welcome :" + Session["UserName"].ToString();
TopNavigationMenu.Style["visibility"] = "visible";
NavigationMenu.Style["visibility"] = "visible";
if (Session["FirstTimeLogged"] != null && Convert.ToBoolean(Session["FirstTimeLogged"]) == true)
{
TopNavigationMenu.Enabled = false;
NavigationMenu.Enabled = false;
if (!Request.Url.ToString().Contains("MyAccount"))
Response.Redirect("Home.aspx");
}
else
{
GenerateLinks(Session["RoleId"].ToString());
TopNavigationMenu.Enabled = true;
NavigationMenu.Enabled = true;
//TopNavigationMenu.Items[1].Text = "Support <img src='Images/bullet_arrow_down.png' alt='down' title='' />";
if (Request.Url.ToString().Contains("Home"))
Response.Redirect("Default.aspx");
if (!IsPostBack)
{
string strPrevPg = "", strCurrPg = "";
if (Request.UrlReferrer != null)
{
strPrevPg = Request.UrlReferrer.AbsolutePath.ToString();
strPrevPg = strPrevPg.Substring(strPrevPg.IndexOf("/", 1) + 1, strPrevPg.Length - (strPrevPg.IndexOf("/", 1) + 1));
strPrevPg += Request.UrlReferrer.Query.ToString();
}
strCurrPg = Request.Url.AbsolutePath.ToString();
strCurrPg = strCurrPg.Substring(strCurrPg.IndexOf("/", 1) + 1, strCurrPg.Length - (strCurrPg.IndexOf("/", 1) + 1));
bool bFlag;
bFlag = Convert.ToBoolean(Session["goBackPg"]);
if (Session["PrevPg"] != null)
{
if (strCurrPg == Session["PrevPg"].ToString())
{
if (bFlag)
{
Session["CurrPg"] = strCurrPg;
Session["PrevPg"] = "Default.aspx";
bFlag = false;
Session["goBackPg"] = bFlag;
}
else
{
Session["CurrPg"] = strCurrPg;
Session["PrevPg"] = strPrevPg;
}
}
else
{
Session["CurrPg"] = strCurrPg;
Session["PrevPg"] = strPrevPg;
bFlag = false;
Session["goBackPg"] = bFlag;
}
}
}
}
}
}
else
{
Response.Redirect("home.aspx");
}
}
Those browsers are showing you cached content when you press the back button.
You can debug and check, your server is not being hit. This Session code will not work.
You could tell the browser not to cache the page. That way if the user wanted to go back, he would have to reload the content.

Categories