I am trying to have an error message displayed when a username and password are not recognized.
if (rdr.Read())
{
int id = int.Parse(rdr.GetValue(0).ToString());
string fname = rdr.GetString(1);
Session["ID"] = id;
Session["FName"] = fname;
con.Close();
Response.Redirect("Home.aspx");
}
else
{
Response.Redirect("Login.aspx?err='blabla'"); //Display message
}
The following code (Page_Load) is supposed to be invoked in the else statement, but it is not:
public partial class _Default : System.Web.UI.Page
{
protected string err = "";
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Form.Count > 0)
{
err = Request.Form["err"];
}
}
}
Why is this the case?
Thank you all so much!
This is a GET value in the query string, not a POST value in the form. You can use Request.QueryString[] or Request[] which contains POST and GET values.
if (Request.QueryString.Count > 0)
{
err = Request.QueryString["err"];
}
or
if (Request.Count > 0)
{
err = Request["err"];
}
Also, the query string value belongs to the Login page, so you won't be able to access it from _Default. Move your Page_Load logic to Login.aspx.cs.
Generally speaking, based off the class name _Default, I believe you have placed this code in the Default.aspx page. Place the code in the Load for the Login.aspx page. And then also follow the direction provided by jrummell.
Related
I have a View button on my webpage. As soon as a user clicks on this button, through a web service data is fetched and then data is bound to grid view. But when the grid view loads it only shows the number of rows mentioned in PageSize property of the grid and does not show page numbers.
private void FetchData(ref DataTable dt)
{
string s_strResult = "";
string s_strQuery = "";
string s_strQueryType = "";
try
{
grdSearchResult.DataSource = dt.DataSet.Tables["Result"];
grdSearchResult.DataBind();
tblSearchResult.Visible = true;
lblSearchResult.Text = "Total Items:" + dt.DataSet.Tables["Result"].Rows.Count;
}
}
The Result DataSet contains 5000 rows with 30 columns each. When the gridView loads all I can see is just 100 records (as PageSize=100). How can I page the results? The data needs to be fetched at button click only. The code for gridView page index change is as follows:
protected void grdSearchResult_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
try
{
grdSearchResult.PageIndex = e.NewPageIndex;
grdSearchResult.DataBind();
}
catch (Exception ex)
{
DisplayMessage(GlobalClass.enumMsgType.Error, ex.Message);
}
}
Hello Rishik please check below link for gridview paging:
http://www.codeproject.com/Articles/816953/How-To-Implement-Paging-in-GridView-Control-in-ASP
http://www.c-sharpcorner.com/UploadFile/rohatash/gridview-paging-sample-in-Asp-Net/
You can store your data in a Viewstate or Session variable, I recommend to use a property as wrapper like this:
private DataTable dtStored
{
get { return (ViewState["dt"] == null) ? null : (DataTable)ViewState["dt"]; }
set { ViewState["dt"] = value; }
}
now you can bind your DataTable and save it in the property:
private void FetchData(ref DataTable dt)
{
string s_strResult = "";
string s_strQuery = "";
string s_strQueryType = "";
try
{
dtStored = dt.DataSet.Tables["Result"];
grdSearchResult.DataSource = dtStored;
grdSearchResult.DataBind();
tblSearchResult.Visible = true;
lblSearchResult.Text = "Total Items:" + dt.DataSet.Tables["Result"].Rows.Count;
}
}
and in the IndexPageChanging method just add a line:
protected void grdSearchResult_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
try
{
grdSearchResult.DataSource = dtStored;
grdSearchResult.PageIndex = e.NewPageIndex;
grdSearchResult.DataBind();
}
catch (Exception ex)
{
DisplayMessage(GlobalClass.enumMsgType.Error, ex.Message);
}
}
If your data is too large maybe it could be better to store it in a Session variable than in a Viewstate, because the second one is going to travel from the Client to the Server and from the Server to the Client in every Postback while you stay in the same page or until you set the variable to null
I'm trying to make a script that checks, if a user has the right age before joining a team. If the user age doesn't match the team age, the script should stop at this page, and require the user to click the button "BackToLastPageBtn" go back to the previous page, which uses a variable called "BackToLastPage", which gets its value from 'Session["currentUrl"]', before it is reset at Page_load.
The problem is, that it tells me the value is null, when clicking the button.
I don't know why it is null, when i add the value to "BackToLastPage", BEFORE resetting Session["currentUrl"]. I hope someone can tell me, and guide me in the right direction.
The CodeBehind - script
public partial class JoinTeam : System.Web.UI.Page
{
//Defining Go back variable
private string BackToLastPage;
protected void Page_Load(object sender, EventArgs e)
{
int BrugerId = Convert.ToInt32(Session["BrugerId"]);
int TeamId = Convert.ToInt32(Request.QueryString["HoldId"]);
//Adding value to go back variable from sessionurl
BackToLastPage = (string)Session["CurrentUrl"];
//Resets sessionurl.
Session["CurrentUrl"] = null;
if (Session["brugerId"] != null)
{
if (ClassSheet.CheckIfUserAgeMatchTeamAge(BrugerId, TeamId))
{
ClassSheet.JoinATeam(BrugerId, TeamId);
if (BackToLastPage != null)
{
//Uses the new savedUrl variable to go back to last page.
Response.Redirect(BackToLastPage);
}
else
{
Response.Redirect("Default.aspx");
}
}
else
{
AgeNotOk.Text = "Du har ikke den rigtige alder til dette hold";
}
}
else
{
//Not saving last page. Need to find solution.
Response.Redirect("Login.aspx");
}
}
//NOT WORKING...
protected void BackToLastPageBtn_Click(object sender, EventArgs e)
{
//Go back button
//Response.Write(BackToLastPage);
Response.Redirect(BackToLastPage);
}
}
Since you are setting session["CurrentURL"] to null in page_load. When the event is fired it no longer exists. Below is code that i got it working. I had to cut some of your code out since i dont have the definition of all your classes. Private properties do not persist through postbacks. If you wanted it to work the way you have it, you should save the previoius url in a hidden field on the page itself.
Page One:
protected void Page_Load(object sender, EventArgs e)
{
Session["CurrentUrl"] = Request.Url.ToString();
Response.Redirect("~/SecondPage.aspx");
}
Page Two:
private string BackToLastPage { get { return (Session["CurrentUrl"] == null) ? "" : Session["CurrentUrl"].ToString(); } }
protected void Page_Load(object sender, EventArgs e)
{
int BrugerId = Convert.ToInt32(Session["BrugerId"]);
int TeamId = Convert.ToInt32(Request.QueryString["HoldId"]);
if (Session["brugerId"] != null)
{
//CUT CODE OUT DONT HAVE YOUR DEFINITIONS
Response.Write("brugerid was not null");
}
}
protected void BackToLastPageBtn_Click(object sender, EventArgs e)
{
//YOU SHOULD SET THE CURRENT URL TO NULL HERE.
string tempUrl = BackToLastPage;
Session["CurrentUrl"] = null;
Response.Redirect(tempUrl);
}
You can also try this, Store the return url in a hiddenfield and only set it if it is not a page postback:
Markup HTML:
<form id="form1" runat="server">
<div>
<asp:Button ID="btnOne" runat="server" OnClick="BackToLastPageBtn_Click" Text="Button One" />
<asp:HiddenField ID="hfPreviousUrl" runat="server" />
</div>
</form>
Code Behind:
private string BackToLastPage //THIS WILL NOW PERSIST POSTBACKS
{
get { return hfPreviousUrl.Value; }
set { hfPreviousUrl.Value = value;}
}
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)//THIS PREVENTS THE VALUE FROM BEING RESET ON BUTTON CLICK
BackToLastPage = (string)Session["CurrentUrl"];
int BrugerId = Convert.ToInt32(Session["BrugerId"]);
int TeamId = Convert.ToInt32(Request.QueryString["HoldId"]);
//Resets sessionurl.
Session["CurrentUrl"] = null;
if (Session["brugerId"] != null)
{
Response.Write("brugerID was not null");
}
else
{
//REMOVED FOR TEST PURPOSES
//Response.Redirect("Login.aspx");
}
}
protected void BackToLastPageBtn_Click(object sender, EventArgs e)
{
Response.Redirect(BackToLastPage);
}
I tried to link default1.aspx and default 2.aspx.
What I'm trying to do is to display calculated results in default1.aspx when clicking confirm button in default2.aspx.
I run the codes but it doesn't work really.
How can I fix this?
I wrote the codes in default1.aspx below:
protected void confirmBookingButton_Click(object sender, ImageClickEventArgs e)
{
Response.Redirect("RoomBookingMain.aspx");
Session["confirmBooking"] = "confirm";
Session["totalBooking"] = calculateTextBox.Text;
}
and then I wrote other codes in default2.aspx like:
public partial class RoomBookingMain : System.Web.UI.Page
{
static int nbBookingInt = 0;
static int totalRevenueInt = 0;
}
protected void Page_Load(object sender, EventArgs e)
{
bookingNbLabel.Text = nbBookingInt.ToString();
totRevenueLabel.Text = totalRevenueInt.ToString();
string confirmBooking = (string)(Session["confirmBooking"]);
if ((string)(Session["confirmBooking"]) == "confirm")
{
nbBookingInt += 1;
totalRevenueInt += int.Parse(Session["totalBooking"].ToString());
Session["confirmBooking"] = "no current booking";
}
}
Session["confirmBooking"] = "confirm";
Session["totalBooking"] = calculateTextBox.Text;
Response.Redirect("RoomBookingMain.aspx");
Assign Session before Response.Redirect(). Redirect method will stop the execution at that point.
If you need to pass the data only to next page and if no secure data is involved you can use QueryStrings.
I have the following code to check that a query string has not changed:
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
Label_Error.Visible = false;
string query_string = Request.QueryString["GUID"].ToString();
Session["GUID"] = query_string;
}
else
{
string GUID = "";
try
{
GUID = Session["GUID"].ToString();
}
catch (Exception)
{
Session.Abandon();
Response.Redirect("CheckOutErrorPage.htm");
return;
}
if (GUID.Equals(Request.QueryString["GUID"].ToString()) == false)
{
Session.Abandon();
Response.Redirect("CheckOutErrorPage.htm");
}
}
}
Now, I have this code in a button-click event handler to check that the value of the query string has not changed (again):
protected void ImageButton_LogIn_Click(object sender, ImageClickEventArgs e)
{
Validation val = new Validation();
string GUID = "";
string query_string = "";
try
{
GUID = Session["GUID"].ToString();
query_string = Request.QueryString["GUID"].ToString();
}
catch (Exception)
{
Session.Abandon();
Response.Redirect("CheckOutErrorPage.htm");
return;
}
if (val.EmptyString(GUID) == true || val.checkTransactionGUIDExists(GUID) == false || GUID.Equals(query_string) == false)
{
Session.Abandon();
Response.Redirect("CheckOutErrorPage.htm");
}
Now, the problems are two:
1) if I change the query string in the URL and click on the button, the user is not redirected to the error page.
2) if I change the query string in the URL and hit enter in the address bar, the user is not redirected to the error page.
What I want basically is that, when the user is redirected to the web page, it saves the query string into a session. If the user changes the value of the query string in the address bar, and either pressed enter in the address bar or presses my button, he is redirected to the error page.
However, my code is failing. Can anyone help please? Thanks :)
How about this instead?
protected void Page_Load(object sender, EventArgs e)
{
// Always get the query string no matter how the user go to this page
string query_string = Request.QueryString["GUID"].ToString();
// Only store the query string in Session if there is nothing in Session for it
if(null == Session["GUID"])
{
Session["GUID"] = query_string;
}
if (!this.IsPostBack)
{
Label_Error.Visible = false;
}
// Always check to see if the query string value matches what is in Session
string GUID = "";
try
{
GUID = Session["GUID"].ToString();
}
catch (Exception)
{
Session.Abandon();
Response.Redirect("CheckOutErrorPage.htm");
return;
}
if (GUID.Equals(Request.QueryString["GUID"].ToString()) == false)
{
Session.Abandon();
Response.Redirect("CheckOutErrorPage.htm");
}
This should solve your problem of the Session value being overwritten when a query string is put into the address bar and enter is pressed by the user.
I think you problem is that Response.Redirect needs the false at the final of the sentence like Response.Redirect("CheckOutErrorPage.htm", false); becouse that you have it inside the try cath the error will be throw.
I hope that help you.
I have a login form "frmLog()" which has text box for username and password, now I want to get the input text from username text box. Please see the code below and don't be confuse I am using mysql database so the other syntax code are not important.
This is the Login form "frmLog()"
private void button1_Click(object sender, EventArgs e)
{
ApareceCrudLib a = new ApareceCrudLib("localhost", "root", "", "cashieringdb");
string user = txtLogin.Text;
string pass = txtPassword.Text;
string query = "SELECT * FROM register WHERE username='" + user + "' AND password=MD5('" + pass + "')";
int result = a.Count(query);
if (result == 1)
{
frmMain main = new frmMain();
main.ShowDialog();
this.Dispose();
}
else
{
MessageBox.Show("Login Failed! Try Again");
txtLogin.Text = "";
txtPassword.Text = "";
}
}
This is the other form where I want to retrieve the code "frmMain()". Please see the public void dataLog() that is the part of code that I attempt to get the input value from frmLog.
private void frmMain_Load(object sender, EventArgs e)
{
a = new ApareceCrudLib("localhost", "root", "", "cashieringdb");
loadDataGridView_Main();
dataLog();
}
public void loadDataGridView_Main()
{
dgvMain.Rows.Clear();
List<string>[] detailList = a.mysqlSelect("Select * From sales");
for (int i = 0; i < detailList.Length; i++)
{
dgvMain.Rows.Add(detailList[i][0], detailList[i][1], detailList[i][2], detailList[i][3]);
}
}
public void dataLog()
{
frmLog kk = new frmLog();
txtLog.Text= kk.txtLogin.ToString();
}
This is the wrong result
The result must be the username from frmLog() example "client123". What do you think is wrong here?
kk.txtLogin.ToString(), returns a string that represents the current object. In this case your current object is TextBox.
Instead display the TextBox, you should show the TextBox's value.
Change that code to:
kk.txtLogin.Text;
UPDATE
If you want to display the txtLogin value from frmLog in frmMain, you can declare static variable in frmLog that store the txtLogin value.
in frmLog:
public static String LOGIN_USER = "";
Then in button1_Click:
if (result == 1)
{
LOGIN_USER = txtLogin.Text;
frmMain main = new frmMain();
main.ShowDialog();
this.Dispose();
}
in frmMain_Load:
public void dataLog()
{
txtLog.Text= frmLog.LOGIN_USER;
}
In your datalog() Methode is the first error.
Replace:txtLog.Text= kk.txtLogin.ToString();
With:txtLog.Text= kk.txtLogin.Text;
In:
public void dataLog()
{
frmLog kk = new frmLog();
txtLog.Text= kk.txtLogin.ToString();
}
You create a new frmlog object without showing it, so the textbox is empty. You should retrieve the text from the text box after the user input.
It is so because you are trying to read data from a new instance of your frmLog();
In you frmMain, do not write this :
frmLog kk = new frmLog();
instead create a public reference in your form class
public frmLog kk;
and then, In your frmLog,
frmMain main = new frmMain();
main.kk=this;
main.ShowDialog();
this will create a reference to your first form in second form.