I'm have problemas to work with Session in my project ASp.NEt c# in IE9.
Sometimes occured error:
"Object reference not set to an instance of as object"
Other problem is that in IE9, sometimes not save my Session to change Idiom to others pages.
In Chrome all works good!
Below is my Page_Load and CarregaGrid(). This problem occured in sometimes, no all time, and in any page no in all page or just in one specific page.
public void CarregaGrid()
{
var listByGroupM = new ManageUsers().ConsultUsersGroupM();
if (listByGroupM != null)
{
this.GridView1.DataSource = listByGroupM;
if (listByGroupM.Count != 0)
{
this.GridView1.DataBind();
GridView1.HeaderRow.TableSection = TableRowSection.TableHeader;
}
}
if (divModify.Visible == true)
{
foreach (GridViewRow row in GridView1.Rows)
{
string idioma = CultureInfo.CurrentCulture.TwoLetterISOLanguageName.ToString();
if (Session["idioma"].ToString() != null)
{
idioma = Session["idioma"].ToString();
}
Idioma.MudaCultura(idioma);
Button btnDelete = (Button)row.FindControl("btnDelete");
btnDelete.Text = Idioma.RetornaMensagem("btnDelete");
string UserName = row.Cells[1].Text;
PrincipalContext insPrincipalContext = new PrincipalContext(ContextType.Domain, "x.com", "x", "xxx");
UserPrincipal insUserPrincipal = UserPrincipal.FindByIdentity(insPrincipalContext, UserName);
if (insUserPrincipal == null)
{
row.Cells[2].Text = "";
row.Cells[3].Text = "";
}
else
{
string Email = insUserPrincipal.EmailAddress;
row.Cells[2].Text = Email;
string DisplayName = insUserPrincipal.DisplayName;
row.Cells[3].Text = DisplayName;
}
}
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string idioma = CultureInfo.CurrentCulture.TwoLetterISOLanguageName.ToString();
if (Session["idioma"].ToString() != null)
{
idioma = Session["idioma"].ToString();
}
Idioma.MudaCultura(idioma);
Label1.Text = Idioma.RetornaMensagem("lblUserAdd");
CarregaGrid();
}
}
protected void pt_OnChange(object sender, EventArgs e)
{
Idioma.MudaCultura("pt");
Label1.Text = Idioma.RetornaMensagem("lblUserAdd");
CarregaGrid();
Session["idioma"] = "pt";
}
protected void en_OnChange(object sender, EventArgs e)
{
Idioma.MudaCultura("en");
Label1.Text = Idioma.RetornaMensagem("lblUserAdd");
CarregaGrid();
Session["idioma"] = "en";
}
protected void es_OnChange(object sender, EventArgs e)
{
Idioma.MudaCultura("es");
Label1.Text = Idioma.RetornaMensagem("lblUserAdd");
CarregaGrid();
Session["idioma"] = "es";
}
replace
if (Session["idioma"].ToString() != null)
with
if (Session["idioma"] != null)
If the session object is NULL, then calling .ToString() will throw an error.
Change:
if (Session["idioma"].ToString() != null)
to:
if (Session["idioma"] != null)
Related
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Request.Cookies["UserName"] != null && Request.Cookies["Password"] != null)
{
txtUserName.Text = Request.Cookies["UserName"].Value;
txtPass.Attributes.Add("value", Convert.ToString(Request.Cookies["Password"].Value));
CheckBox1.Checked = true;
}
}
}
protected void btnLogIn_Click(object sender, EventArgs e)
{
if (dt.Rows.Count != 0)
{ }
else
{
lblMsg.Visible = true;
lblMsg.Text = "Login In Failed";
}
ClearField();
}
}
protected void ClearField()
{
txtUserName.Text = string.Empty;
txtPass.Text = string.Empty;
}
When my else condition execute. it not empty my txtPass Textbox instead if i write wrong password it display correct password in textbox.
i think something wrong with Cookie but idk how to solve it.
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.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Request.Browser.Cookies)
{
if (Request.QueryString["check"] == null)
{
HttpCookie cookie = new HttpCookie("testcookie");
Response.Cookies.Add(cookie);
Response.Redirect("Default.aspx?check=1");
}
else
{
HttpCookie cookie = Request.Cookies["testcookie"];
if(cookie==null)
{
Label1.Text = "enable cookies";
}
}
}
else
{
Label1.Text = "cookies not supported:";
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
HttpCookie cookie = new HttpCookie("userinfo");
cookie["name"] = TextBox1.Text;
cookie["email"] = TextBox2.Text;
//cookie.Expires = DateTime.Now.AddDays(30);
Response.Cookies.Add(cookie);
Response.Redirect("Default2.aspx");
}
It's not working correctly.
See the following link.
http://forums.asp.net/t/1044823.aspx?How+to+check+cookies+enabled+in+a+web+browser+
The only way to check is set a cookie then redirect it and again check if you are able to access it or not. So try below method mentioned in above link.
protected void Page_Load(object sender, EventArgs e)
{
if (this.IsCookieDisabled())
errorMsgLabel.Text = Resources.Resource.BrowserDontSupportCookies;
}
private bool IsCookieDisabled()
{
string currentUrl = Request.RawUrl;
if (Request.QueryString["cookieCheck"] == null)
{
try
{
HttpCookie c = new HttpCookie("SupportCookies", "true");
Response.Cookies.Add(c);
if (currentUrl.IndexOf("?") > 0)
currentUrl = currentUrl + "&cookieCheck=true";
else
currentUrl = currentUrl + "?cookieCheck=true";
Response.Redirect(currentUrl);
}
catch(Exception ex)
{
return false;
}
}
if (!Request.Browser.Cookies || Request.Cookies["SupportCookies"] == null)
return true;
return false;
}
I'm new to asp.net and needs some help. I have a gridview with paging for every 20 records per page, I have a search button outside the gridview. What I need to do is when I click the search button, the results must be bind to gridview(which is happening now), however when the records are more than the pagesize and I need to go to the next page of the grid, the binding is lost and the binded records are the ones form the page on load event. below is my code sample.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
}
}
public void BindData()
{
{
List<EventFile> eventFile = new List<EventFile>();
eventFile = CoMailAssociationDAL.GetUploadFileUnAssigned(0, "", "", "U");
if (gvwAssociation.DataSource == null)
{
gvwAssociation.DataSource = eventFile;
gvwAssociation.DataBind();
}
}
}
protected void btnSearch_Click(object sender, EventArgs e)
{
int uFlag = 0;
string uploadFlag = this.ddlUploadDate.SelectedValue;
string fileName = this.txtSearchText.Text;
string uploadDt = this.txtDate.Text;
string status = this.ddlStatus.SelectedValue.ToString();
bt = true;
if (status == "Un-Assigned")
{
status = "U";
}
else if (status == "Assigned")
{
status = "A";
}
else
{
status = "B";
}
if ((uploadFlag == "On") && (uploadDt == ""))
{
uFlag = 0;
}
else if (uploadFlag == "On")
{
uFlag = 1;
}
else if (uploadFlag == "OnorBefore")
{
uFlag = 2;
}
else
{
uFlag = 3;
}
fileSearch = CoMailAssociationDAL.SearchFile(uFlag, fileName, uploadDt, status);
gvwAssociation.DataSource = fileSearch;
gvwAssociation.DataBind();
}
protected void gvwAssociation_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
//SaveSelectedValues();
gvwAssociation.PageIndex = e.NewPageIndex;
//BindData();
//PopulateSelectedValues();
}
First of all you should have the following event handler for paging
protected void gvwAssociation_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvwAssociation.PageIndex = e.NewPageIndex;
bindGridWithFilter();
}
Then, move your search/ filter logic within the search button to a private method (say "bindGridWithFilter")
TIP: Try to combine both BindData and bindGridWithFilter so when there's no filter you display all records
UPDATE
Here's some refactored code for you to get an idea what I meant above.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
bindGridWithFilter();
}
}
protected void gvwAssociation_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvwAssociation.PageIndex = e.NewPageIndex;
bindGridWithFilter();
}
protected void btnSearch_Click(object sender, EventArgs e)
{
bindGridWithFilter();
}
private void bindGridWithFilter()
{
List<EventFile> eventFile = new List<EventFile>();
eventFile = CoMailAssociationDAL.GetUploadFileUnAssigned(0, "", "", "U");
if (gvwAssociation.DataSource == null)
{
// If you don't have a filter you show all records
gvwAssociation.DataSource = eventFile;
gvwAssociation.DataBind();
}
else
{
// This is same as the logic in your search button
// display only the filtered records
int uFlag = 0;
string uploadFlag = this.ddlUploadDate.SelectedValue;
string fileName = this.txtSearchText.Text;
string uploadDt = this.txtDate.Text;
string status = this.ddlStatus.SelectedValue.ToString();
bt = true;
if (status == "Un-Assigned")
{
status = "U";
}
else if (status == "Assigned")
{
status = "A";
}
else
{
status = "B";
}
if ((uploadFlag == "On") && (uploadDt == ""))
{
uFlag = 0;
}
else if (uploadFlag == "On")
{
uFlag = 1;
}
else if (uploadFlag == "OnorBefore")
{
uFlag = 2;
}
else
{
uFlag = 3;
}
List<EventFile> fileSearch = CoMailAssociationDAL.SearchFile(uFlag, fileName, uploadDt, status);
gvwAssociation.DataSource = fileSearch;
gvwAssociation.DataBind();
}
}
This should work.
I have a menu and label in my master page which i want to update depending on the type of user logged in.
Firstly am removing few MenuItems from the menu that is working fine but its not showing up in the master page. Instead the old menu is only seen with all the menu items for limited user also. When i debug the label text shows what i have set but when page loads its not updating too.
Am using the following code.
Label lbWelcomeMessage = new Label();
protected void Page_Load(object sender, EventArgs e)
{
Master.FindControl("CAMenu").Visible = false;
}
protected void btnLogin_Click(object sender, EventArgs e)
{
string userName = txtUsername.Text;
string password = txtPassword.Text;
Common common = new Common();
DataTable tab = new DataTable();
tab= common.GetUserDetails(userName);
string firstName = string.Empty;
string userPassword = string.Empty;
string RoleID=string.Empty;
if (tab.Rows.Count == 1)
{
firstName = tab.Rows[0][2].ToString();
userPassword = tab.Rows[0][4].ToString();
RoleID = tab.Rows[0][5].ToString();
}
if (userPassword == password)
{
if (RoleID != "1")
{
Menu CAMenu = new Menu();
CAMenu = (Menu)Master.FindControl("CAMenu");
int count = CAMenu.Items.Count;
for (int i = 3; i > 0; i--)
{
string text = CAMenu.Items[i - 1].Text;
CAMenu.Items.RemoveAt(i - 1);
}
lbWelcomeMessage = (Label)Master.FindControl("lbLoginMessage");
lbWelcomeMessage.Text = "Welcome"+" "+ firstName;
((SiteMaster)Page.Master).MyText = lbWelcomeMessage.Text;
Response.Redirect("AdHocSMS.aspx");
}
else
{
lbWelcomeMessage = (Label)Master.FindControl("lbLoginMessage");
lbWelcomeMessage.Text = lbWelcomeMessage.Text+" "+firstName ;
Response.Redirect("NewTemplate.aspx");
}
}
}
I assume you have written this code in your login.aspx. When login button is clicked then it takes you to another page and all the life cycle of page is run again. and master page contents are reset.
The solution to this problem could be. Move this logic to your master page code like
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
if (Session.Count == 0 || Session["Username"] == null)
Response.Redirect("~/Login.aspx", true);
CheckRole();
}
public void CheckRole()
{
if (System.Web.HttpContext.Current.Session.Count > 0)
{
tab= common.GetUserDetails(Session["Username"]);
if (tab.Rows.Count == 1)
{
firstName = tab.Rows[0][2].ToString();
userPassword = tab.Rows[0][4].ToString();
RoleID = tab.Rows[0][5].ToString();
}
if (RoleID != "1")
{
Menu CAMenu = new Menu();
int count = CAMenu.Items.Count;
for (int i = 3; i > 0; i--)
{
string text = CAMenu.Items[i - 1].Text;
CAMenu.Items.RemoveAt(i - 1);
}
//your label logic
lbWelcomeMessage.Text = "Welcome"+" "+ firstName;
((SiteMaster)Page.Master).MyText = lbWelcomeMessage.Text;
Response.Redirect("AdHocSMS.aspx");
}
else
{
//Logic
Response.Redirect("NewTemplate.aspx");
}
}
else
{
Session.Abandon();
Response.Redirect("~/Login.aspx", true);
}
}
You have to put a UserId or Username in Session this is the one disadvantage but for every page you dont have to worry about anything.
for life cycle read this article http://msdn.microsoft.com/en-us/library/ms178472.aspx
let me know if it solves or not.
What i did is something like this
In Site.Mater:-
public void CheckRole()
{
try
{
if (System.Web.HttpContext.Current.Session.Count > 0)
{
string firstName = string.Empty;
// string userPassword = string.Empty;
string RoleID = string.Empty;
Common common = new Common();
DataTable tab = new DataTable();
string userName = (string)Session["UserName"];
User user = new User(userName);
tab = user.GetUserDetails(userName);
if (tab.Rows.Count == 1)
{
firstName = tab.Rows[0][1].ToString();
RoleID = tab.Rows[0][3].ToString();
}
if (RoleID != "1")
{
int count = CAMenu.Items.Count;
if (count == 5)
{
for (int menuCount = 3; menuCount > 0; menuCount--)
{
string text = CAMenu.Items[menuCount - 1].Text;
CAMenu.Items.RemoveAt(menuCount - 1);
}
}
lbLoginMessage.Text = "Welcome," + " " + firstName;
loginStatus.Visible = true;
}
else
{
lbLoginMessage.Text = "Welcome," + " " + firstName;
loginStatus.Visible = true;
}
}
else
{
Session.Abandon();
Response.Redirect("~/Login.aspx", true);
}
}
catch (Exception ex)
{
new Logger().Log("ShortCom.SiteMaster.CheckRole()", ex.Message);
Response.Redirect("~/Error.aspx");
}
}
In Login.Apsx:-
protected void Page_Load(object sender, EventArgs e)
{
try
{
Master.FindControl("CAMenu").Visible = false;
Master.FindControl("loginStatus").Visible = false;
}
catch (Exception ex)
{
new Logger().Log("ShortCom.Login.btnLogin_Click(object sender, EventArgs e)", ex.Message);
Response.Redirect("~/Error.aspx");
}
}
protected void LoadMessageBox(string MessageID)
{
try
{
messages = new GUIMessages();
popupExtend = new ModalPopupExtender();
lbMessage = (Label)Master.FindControl("label5");
lbMessage.Text = messages.GetGUIMessage(GUIModule.Login, MessageID);
popupExtend = (ModalPopupExtender)Master.FindControl("popupExtender");
popupExtend.Show();
}
catch (Exception ex)
{
new Logger().Log("ShortCom.Login.LoadMessageBox(string MessageID)", ex.Message);
Response.Redirect("~/Error.aspx");
}
}
protected void btnLogin_Click(object sender, EventArgs e)
{
try
{
string userName = txtUsername.Text;
string password = txtPassword.Text;
if (userName == string.Empty && password == string.Empty)
{
LoadMessageBox("5");
txtUsername.Focus();
return;
}
if (userName == string.Empty)
{
LoadMessageBox("1");
txtUsername.Focus();
return;
}
else if (password == string.Empty)
{
LoadMessageBox("3");
txtPassword.Focus();
return;
}
User user = new User(userName);
DataTable tab = new DataTable();
tab = user.GetUserDetails(userName);
string firstName = string.Empty;
string userPassword = string.Empty;
string RoleID = string.Empty;
string userID = string.Empty;
Session["UserName"] = userName;
if (tab.Rows.Count == 0)
{
LoadMessageBox("6");
txtPassword.Text = string.Empty;
txtUsername.Text = string.Empty;
txtUsername.Focus();
return;
}
if (tab.Rows.Count == 1)
{
userID = tab.Rows[0][0].ToString();
firstName = tab.Rows[0][1].ToString();
userPassword = tab.Rows[0][2].ToString();
RoleID = tab.Rows[0][3].ToString();
Session["UserID"] = userID;
}
//if (firstName != userName)
//{
// LoadMessageBox("2");
// txtUsername.Focus();
// return;
//}
//else
{
if (userPassword == password)
{
Response.Redirect("~/Default.aspx");
}
else
{
LoadMessageBox("4");
txtPassword.Focus();
return;
}
}
}
catch (Exception ex)
{
new Logger().Log("ShortCom.Login.btnLogin_Click(object sender, EventArgs e)", ex.Message);
Response.Redirect("~/Error.aspx");
}
}