protected void submitLogin(object sender, EventArgs e)
{
string connStr = ConfigurationManager.ConnectionStrings["tropicalConnectionString"].ConnectionString;
string queryString = "select * from tblUserLogin where userId='" + useridtextbox.Text
+ "' and password ='" + passwordtextbox.Text + "'";
Console.WriteLine(queryString);
conn = new OleDbConnection(connStr);
conn.Open();
cmd = new OleDbCommand(queryString, conn);
reader = cmd.ExecuteReader();
userId = "";
if (reader.HasRows && reader.Read())
{
userId = reader.GetString(reader.GetOrdinal("UserId"));
}
if (reader.HasRows)
{
Session["uid"] = userId;
Response.BufferOutput = true;
Response.Redirect("/UI/Products.aspx", false);
bool ck = remembercheckbox.Checked;
if (ck)
{
Response.Cookies["UserName"].Expires = DateTime.Now.AddDays(7);
Response.Cookies["UserName"].Value = useridtextbox.Text.Trim();
}
else
{
HttpCookie myCookie = new HttpCookie("UserSettings");
Response.Cookies["UserName"].Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(myCookie);
}
}
else
{
passwordtextbox.Text = "invalid user";
}
Here's a snippet of my login content page
<div class="login">
<asp:CheckBox ID="remembercheckbox" TextAlign="left" runat="server" text="Remember my Id" checked="false" OnCheckedChanged="clickCkbx" />
<asp:Button ID="loginButton" CssClass="loginButton" runat="server" text="Login" OnClick="submitLogin" />
</div>
I'm trying to implement a remember user id function and practicing it with cookie. The problem is that when I uncheck the box for "remembercheckbox", the value in remembercheckbox.Checked keep returning true and thus I cannot go into the else statement and destroy the cookie.
Thanks in advance!
Just solve the problem. I had this as my page_load. and when the button was clicked button, because the postback mechanism, the page got reloaded and Page_Load was called and thus remembercheckbox.Checked was set to true again.
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Cookies["UserName"] != null)
{
remembercheckbox.Checked = true;
useridtextbox.Text = Request.Cookies["UserName"].Value;
}
chk = remembercheckbox.Checked;
}
solve this by checking !Page.IsPostBack and then assign the cookie
Related
I set attributes into a dropdownlist
the problem is that when I try to read them in a button click I get null !!
I am not sure of this is something to do with the postback or not but you will see my code below
Why is that and how to fix it?
This is my Code
protected void ddlReps_DataBound(object sender, EventArgs e)
{
foreach (System.Data.DataRow row in dt.Rows)
{
ddlReps.Items.FindByValue(row["ReportID"].ToString()).Attributes.Add("ReportPath", row["ReportPath"].ToString());
ddlReps.Items.FindByValue(row["ReportID"].ToString()).Attributes.Add("ReportServer", row["ReportServer"].ToString());
}
string AttribValue1 = ddlReps.SelectedItem.Attributes["ReportPath"];
//When I check here I can see the valu
}
protected void btnViewReport_Click(object sender, EventArgs e)
{
string AttribValue2 = ddlReps.SelectedItem.Attributes["ReportPath"];
//Here is null :(
}
ALso here is the page load code
protected void Page_Load(object sender, EventArgs e)
{
if (!User.Identity.IsAuthenticated) // if the user is already logged in
{
Response.Redirect("~/AccessDenied.aspx");
}
if (!Page.IsPostBack)
{
if (Session["USERNAME"] != null)
{
lblWelcome.Text = "Welcome back " + Session["USERNAME"].ToString();
}
string connStr = ConfigurationManager.ConnectionStrings["Main"].ConnectionString;
SqlConnection conn = new SqlConnection(connStr);
try
{
conn.Open();
SqlCommand cmd = new SqlCommand("mySP", conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
cmd.CommandType = CommandType.StoredProcedure;
da.Fill(dt);
if (dt.Rows.Count > 0)
{
//Populate your DropDownList
ddlReps.DataSource = dt;
ddlReps.DataTextField = "ReportName";
ddlReps.DataValueField = "ReportID";
ddlReps.DataBind();
}
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Fetch Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
}
}
and here is the markeup for the ddl
the asp:ScriptManager is used because i am using ReportViewer
<div>
<form id="form2" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<div class="report-module">
<h2>Choose your report</h2>
<asp:DropDownList ID="ddlReps" runat="server" OnDataBound="ddlReps_DataBound" CssClass="ddl" ViewStateMode="Enabled"></asp:DropDownList>
</div>
<rsweb:ReportViewer ID="reportViewer" runat="server" Width="100%" ProcessingMode="Remote" Font-Names="sans-serif" Font-Size="8pt" WaitMessageFont-Names="Verdana" WaitMessageFont-Size="14pt" Height="457px" BackColor="White" Visible="False" SplitterBackColor="51, 181, 229">
</rsweb:ReportViewer>
</form>
</div>
How do I implement my checkbox to stay check as it is even if user redirects to another page? Example, in my code behind when I check the checkbox the system updates the database and it says "Validated" , but when I press GoBackTeacher_Click event it will redirect to another page. In that another page there is a button function there that will redirect to this current page where my code behind function is implemented and checkbox is checked.
Aspx Code:
<div class="container" style="text-align: center; margin: 0 auto;">
<br />
<h1>Validation of Subjects</h1>
<br />
<asp:GridView runat="server" CssClass="table table-hover table-bordered" ID="ValidateSubject" Style="text-align: center"></asp:GridView>
</div>
<div style="float: right; padding-right: 75px;">
<button type="button" runat="server" class="btn btn-success" onserverclick="GoBackTeacher_Click">Go Back</button>
</div>
Code Behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
namespace SoftwareAnalysisAndDesign.SAD
{
public partial class ValidateSubjectTeacher : System.Web.UI.Page
{
CheckBox check = new CheckBox();
protected void Page_Load(object sender, EventArgs e)
{
if (Session["ValidateSubject"] == null)
{
Response.Redirect("TeacherPage.aspx", true);
}
if (!IsPostBack)
{
ValidateSubject.DataSource = Session["ValidateSubject"];
ValidateSubject.DataBind();
}
//Add a checkbox in the last row of GridView Progmatically
foreach (GridViewRow row in ValidateSubject.Rows)
{
check = row.Cells[row.Cells.Count - 1].Controls[0] as CheckBox; //position Check column on last row in gridview
check.Enabled = true;
check.CheckedChanged += ValidateSubject_Click; //Bind the event on the button
check.AutoPostBack = true; //Set the AutoPostBack property to true
}
}
protected void ValidateSubject_Click(object sender, EventArgs e)
{
CheckBox chk = (CheckBox)sender;
GridViewRow grvRow = (GridViewRow)chk.NamingContainer;//This will give row
string validated = "Validated";
string notyetvalidated = "Not yet validated";
string studid = grvRow.Cells[0].Text;
string coursenum = grvRow.Cells[1].Text;
if (chk.Checked)
{
grvRow.Cells[10].Text = validated;
//Open Connection
using (SqlConnection conn = new SqlConnection("Data Source=Keith;Initial Catalog=SAD;Integrated Security=True"))
{
//Open Connection to database
try
{
conn.Open();
}
catch (Exception E)
{
Console.WriteLine(E.ToString());
}
using (SqlCommand cmd = new SqlCommand("Update AssessmentForm set Status = #Validated where StudentID = #studentID and CourseNo = #Coursenumber" ,conn))
{
cmd.Parameters.AddWithValue("#Validated", validated);
cmd.Parameters.AddWithValue("#studentID", studid);
cmd.Parameters.AddWithValue("#Coursenumber", coursenum);
cmd.ExecuteNonQuery();
}
//Close Connection to database
try
{
conn.Close();
}
catch (Exception E)
{
Console.WriteLine(E.ToString());
}
}
}
else
{
grvRow.Cells[10].Text = notyetvalidated;
//Open Connection
using (SqlConnection conn = new SqlConnection("Data Source=Keith;Initial Catalog=SAD;Integrated Security=True"))
{
//Open Connection to database
try
{
conn.Open();
}
catch (Exception E)
{
Console.WriteLine(E.ToString());
}
//query database to update the Status
using (SqlCommand cmd = new SqlCommand("Update AssessmentForm set Status = #Validated where StudentID = #studentID and CourseNo = #Coursenumber", conn))
{
cmd.Parameters.AddWithValue("#Validated", notyetvalidated);
cmd.Parameters.AddWithValue("#studentID", studid);
cmd.Parameters.AddWithValue("#Coursenumber", coursenum);
cmd.ExecuteNonQuery();
}
//Close Connection to database
try
{
conn.Close();
}
catch (Exception E)
{
Console.WriteLine(E.ToString());
}
}
}
}
protected void GoBackTeacher_Click(object sender, EventArgs e)
{
Response.Redirect("TeacherPage.aspx");
}
}
}
To further understand my question, here is an image to further explain it.
This is when I check the checkbox without pressing the go back button
And this where I go pressed the go back button and in the another page there is a proceed button to redirect to this current page where my gridview is located.
There the checkbox is unchecked, and the status says it is validated. How do I implement my code that checkbox stay checked?
Is it something to do with postback? Please help.
UPDATE
I've tried this, it will stay checked my redirecting to this page, but when checkbox is clicked the status will not change from "Validated" to "Not yet validated" it will not change on postback when clicked.
foreach (GridViewRow row in ValidateSubject.Rows)
{
bool isChecked = default(bool);
if (row.Cells[row.Cells.Count - 2].Text.Equals("Validated")) // Here please assign the position of **Status** column.
{
isChecked = true;
check = row.Cells[row.Cells.Count - 1].Controls[0] as CheckBox; //position Check column on last row in gridview
check.Enabled = true;
check.CheckedChanged += ValidateSubject_Click; //Bind the event on the button
check.AutoPostBack = true; //Set the AutoPostBack property to true
check.Checked = isChecked; //Set checkbox checked based on status ;
}
else if (row.Cells[row.Cells.Count - 2].Text.Equals("Not yet validated"))
{
isChecked = false;
check = row.Cells[row.Cells.Count - 1].Controls[0] as CheckBox; //position Check column on last row in gridview
check.Enabled = true;
check.CheckedChanged += ValidateSubject_Click; //Bind the event on the button
check.AutoPostBack = true; //Set the AutoPostBack property to true
check.Checked = isChecked; //Set checkbox checked based on status ;
}
}
In this function, the condition above will not changed the database, instead it will only refresh the page when checkbox is clicked.
protected void ValidateSubject_Click(object sender, EventArgs e)
{
CheckBox chk = (CheckBox)sender;
GridViewRow grvRow = (GridViewRow)chk.NamingContainer;//This will give row
string validated = "Validated";
string notyetvalidated = "Not yet validated";
string studid = grvRow.Cells[0].Text;
string coursenum = grvRow.Cells[1].Text;
if (chk.Checked)
{
grvRow.Cells[10].Text = validated;
//Open Connection
using (SqlConnection conn = new SqlConnection("Data Source=Keith;Initial Catalog=SAD;Integrated Security=True"))
{
//Open Connection to database
try
{
conn.Open();
}
catch (Exception E)
{
Console.WriteLine(E.ToString());
}
using (SqlCommand cmd = new SqlCommand("Update AssessmentForm set Status = #Validated where StudentID = #studentID and CourseNo = #Coursenumber" ,conn))
{
cmd.Parameters.AddWithValue("#Validated", validated);
cmd.Parameters.AddWithValue("#studentID", studid);
cmd.Parameters.AddWithValue("#Coursenumber", coursenum);
cmd.ExecuteNonQuery();
}
//Close Connection to database
try
{
conn.Close();
}
catch (Exception E)
{
Console.WriteLine(E.ToString());
}
}
}
else
{
grvRow.Cells[10].Text = notyetvalidated;
//Open Connection
using (SqlConnection conn = new SqlConnection("Data Source=Keith;Initial Catalog=SAD;Integrated Security=True"))
{
//Open Connection to database
try
{
conn.Open();
}
catch (Exception E)
{
Console.WriteLine(E.ToString());
}
//query database to update the Status
using (SqlCommand cmd = new SqlCommand("Update AssessmentForm set Status = #Validated where StudentID = #studentID and CourseNo = #Coursenumber", conn))
{
cmd.Parameters.AddWithValue("#Validated", notyetvalidated);
cmd.Parameters.AddWithValue("#studentID", studid);
cmd.Parameters.AddWithValue("#Coursenumber", coursenum);
cmd.ExecuteNonQuery();
}
//Close Connection to database
try
{
conn.Close();
}
catch (Exception E)
{
Console.WriteLine(E.ToString());
}
}
}
}
You need to modify your Page_Load method in the section where you are iterating inside gridview rows and assigning handlers and setting checkbox property.
In gridview the status column I guess you are saving it at text not a bit so I compared it as text. See following and implement same.
foreach (GridViewRow row in ValidateSubject.Rows)
{
bool isChecked = default(bool);
if (row.Cells[row.Cells.Count - 1].Text.Equals("Validated")) // Here please assign the position of **Status** column.
isChecked = true;
check = row.Cells[row.Cells.Count - 1].Controls[0] as CheckBox; //position Check column on last row in gridview
check.Enabled = true;
check.CheckedChanged += ValidateSubject_Click; //Bind the event on the button
check.AutoPostBack = true; //Set the AutoPostBack property to true
check.Checked = isChecked //Set checkbox checked based on status ;
}
This is the first time I'm designing a web site. I'm having problem on connecting to my database. None of buttons work on pages. The most important one is Register button. I fill the form correctly but when I press Register button it doesn't register the new user into database. It even doesn't show any error message which I've considered. For example, it doesn't show that You've registered before or Your registration wasn't successful. No error message and no new record in my database. I've removed the captcha code because I thought that may cause problem.Here's my code:
using System;
using System.Data.SqlClient;
using System.Web.UI.WebControls;
public partial class SignUp : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string strname = Cache["TF"] as string;
if (strname != null)
{
(Master.FindControl("Lozv") as Label).Text = strname;
(Master.FindControl("LinkButton1") as LinkButton).Visible = true;
}
else
{
(Master.FindControl("Lozv") as Label).Text = "Guest";
(Master.FindControl("LinkButton1") as LinkButton).Visible = false;
}
}
protected void Button1_Click1(object sender, EventArgs e)
{
string username = txtboxUser.Text;
SqlConnection sqlc = new SqlConnection("Data Source=.; Database=LDatabase; Integrated Security=True");
SqlCommand cmd = new SqlCommand("SELECT dbo.CheckUserName(#UN)");
cmd.Parameters.AddWithValue("#UN", txtboxUser.Text);
sqlc.Open();
Boolean User = Convert.ToBoolean(cmd.ExecuteScalar());
sqlc.Close();
if (User == false) ////////////// if user name is not in DB//////////////
{
SqlConnection sqlca = new SqlConnection();
sqlca.ConnectionString = "data source=. ; database=LDatabase ; integrated security=true";
SqlCommand cmda = new SqlCommand();
cmda.Connection = sqlca;
cmda.CommandText = "INSERT INTO User_Pass values(#UserName,#Pass,#Name,#LastName,#Email,#Date,#Sex,'0')";
cmda.Parameters.AddWithValue("#UserName", txtboxUser.Text);
cmda.Parameters.AddWithValue("#Pass", txtboxPass.Text);
cmda.Parameters.AddWithValue("#Name", txtboxName.Text);
cmda.Parameters.AddWithValue("#LastName", txtboxSurname.Text);
cmda.Parameters.AddWithValue("#Email", txtboxEmail.Text);
cmda.Parameters.AddWithValue("#Date", DateTime.Now);
cmda.Parameters.AddWithValue("#Sex", rbtnGender.SelectedValue.ToString());
cmd.Parameters.AddWithValue("#manager", "No");
sqlca.Open();
int n= cmda.ExecuteNonQuery();
if (n <= 0)
LMsg.Text = "Your registration wasn't successful";
else
{
txtboxName.Text = "";
txtboxSurname.Text = "";
txtboxUser.Text = "";
txtboxPass.Text = "";
txtboxRePass.Text = "";
txtboxEmail.Text = "";
rbtnGender.SelectedIndex = -1;
LMsg.Text = "You registered successfully.";
}
sqlca.Close();
}
else //////////////if user name is in db//////////////
{
LMsg.Text = "This username has already registered.";
}
}
}
Does Captcha have anything to do with this type of problem? Any help would be appreciated.
Put your button like this in the aspx-markup:
<asp:Button ID="btnRegister" runat="server" Click="Button1_Click1" Height="26px" Text="register" Width="88px"/>
It should trigger the method.
Edit: Or bind the event in the Page_Load method (remove the Click-attribute from the button first - from my previous example above).
protected void Page_Load(object sender, EventArgs e)
{
btnRegister.Click += new EventHandler(Button1_Click1);
string strname = Cache["TF"] as string;
[...]
I've got a checkboxlist on my asp.net page. I'm populating it with countries. I've added a "SelectedIndexChanged" event that is supposed to check that if one of the selected countries is Africa, it should make a textbox visible, otherwise visible=false if it is not selected. I have changed the AutoPostback to true. But the problem that I'm having is that it is not doing an autopostback (it's not going into the method at all). Could somebody please help me on this?
This is what I've done:
<div id="div1" style="overflow-x:auto; width:100%; max-width:100%; height:150px; max-height:150px;" runat="server">
<asp:CheckBoxList ID="lstLocations" CssClass="CheckBoxList" runat="server" Width="40%" Height="100%" AutoPostBack="True" OnSelectedIndexChanged="lstLocations_SelectedIndexChanged" >
</asp:CheckBoxList>
</div>
Populating the checkboxlist:
private void CreateRegionList()
{
lstLocations.Items.Clear();
cn = new SqlConnection(GetConnectionString());
SqlCommand myCmd = new SqlCommand("SELECT ID, Region FROM CanonSALeads_Region ORDER BY Region", cn);
cn.Open();
SqlDataReader myReader = myCmd.ExecuteReader();
lstLocations.AutoPostBack = false;
lstLocations.CellPadding = 5;
lstLocations.CellSpacing = 5;
lstLocations.RepeatColumns = 1;
lstLocations.RepeatDirection = RepeatDirection.Vertical;
lstLocations.RepeatLayout = RepeatLayout.Flow;
lstLocations.TextAlign = TextAlign.Right;
lstLocations.CssClass = "CheckBoxList";
if (myReader.HasRows)
{
while (myReader.Read())
{
CheckBox cb = new CheckBox();
cb.ID = myReader[0].ToString();
cb.Text = myReader[1].ToString();
cb.AutoPostBack = false;
cb.CssClass = "CheckBox";
lstLocations.Items.Add(new ListItem(myReader[1].ToString(), myReader[0].ToString()));
lstLocations.Controls.Add(new LiteralControl("<br>"));
}
}
cn.Close();
myReader.Close();
}
And this is my selectedIndexChanged event:
protected void lstLocations_SelectedIndexChanged(object sender, EventArgs e)
{
string value = null;
try
{
foreach (ListItem checkBox in lstLocations.Items)
{
if (checkBox.Selected == true)
{
value = checkBox.Text;
if (value == "Africa")
{
txtCountryOfAfrica.Visible = true;
lblAfricaCountry.Visible = true;
}
}
else
{
value = checkBox.Text;
if (value == "Africa")
{
txtCountryOfAfrica.Visible = false;
lblAfricaCountry.Visible = false;
}
}
}
}
catch (Exception ex)
{
string msg = "Select Error:";
msg += ex.Message;
throw new Exception(msg);
}
}
Page_Load method:
protected void Page_Load(object sender, EventArgs e)
{
string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
txtUser.Text = userName;
if (!IsPostBack)
{
ContainerDocumentation.ActiveTab = tabAddCustomer;
PopulateSector();
CreateRegionList();
PopulateOpportunitySource();
CreatelstProductGroupList();
PopulateStatus();
PopulateTenders();
PopulateOtherOpportunityType();
}
}
My guess: you are calling CreateRegionList in Page_Load without checking the IsPostBack property. That reloads all items from database and prevents this event from being triggered.
So check it:
protected bvoid Page_Load(Objject sender, EventArgs e)
{
if(!IsPostBack)
{
CreateRegionList();
}
}
That's because you have to set true to:
lstLocations.AutoPostBack = true;
I have been doing custom paging for a datagrid where i retrieve only 10 values per page. So, I started doing it this way :
<asp:GridView ID="grid1" runat="server"
> </asp:GridView>
<asp:Button ID="Btn_Previous" CommandName="Previous" runat="server"
OnCommand="ChangePage" Text="Previous" />
<asp:Button ID="Btn_Next" runat="server" CommandName="Next" OnCommand="ChangePage"
Text="Next" />
<asp:Label ID="lblTotalPages" runat="server"></asp:Label>
<asp:Label ID="lblCurrentPage" runat="server"></asp:Label>
protected int currentPageNumber = 1;
protected const int PAGE_SIZE = 10;
protected int startrowindex=1;
protected void Page_Load(object sender, EventArgs e)
{
BindData();
}
private void BindData()
{
using (SqlConnection conn = new SqlConnection("Data Source=NISHANTH-PC\\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=True"))
{
conn.Open();
SqlCommand myCommand = new SqlCommand("GetProductsPaged",
conn);
myCommand.CommandType = CommandType.StoredProcedure;
myCommand.Parameters.AddWithValue("#startRow",
startrowindex);
myCommand.Parameters.AddWithValue("#maximumRows", PAGE_SIZE);
myCommand.Parameters.Add("#totalRows", SqlDbType.Int, 4);
myCommand.Parameters["#totalRows"].Direction = ParameterDirection.Output;
SqlDataAdapter ad = new SqlDataAdapter(myCommand);
DataSet ds = new DataSet();
ad.Fill(ds);
grid1.DataSource = ds;
grid1.DataBind();
double totalRows = (int)myCommand.Parameters["#totalRows"].Value;
lblTotalPages.Text = CalculateTotalPages(totalRows).ToString();
lblCurrentPage.Text = currentPageNumber.ToString();
if (currentPageNumber == 1)
{
Btn_Previous.Enabled = false;
if (Int32.Parse(lblTotalPages.Text) > 0)
{
Btn_Next.Enabled = true;
}
else
Btn_Next.Enabled = false;
}
else
{
Btn_Previous.Enabled = true;
if (currentPageNumber == Int32.Parse(lblTotalPages.Text))
Btn_Next.Enabled = false;
else Btn_Next.Enabled = true;
}
conn.Close();
}
}
private int CalculateTotalPages(double totalRows)
{
int totalPages = (int)Math.Ceiling(totalRows / PAGE_SIZE);
return totalPages;
}
protected void ChangePage(object sender, CommandEventArgs e)
{
switch (e.CommandName)
{
case "Previous":
currentPageNumber = currentPageNumber - 1;
startrowindex = startrowindex - 10;
break;
case "Next":
currentPageNumber = currentPageNumber + 1;
startrowindex = startrowindex + 10;
break;
}
BindData();
}
Basically, my problem has been that the grid works fine when the page loads. Then, since previous is hidden, when i click next it goes to second page and retrieves values perfectly. But when i click either on next or previous now, it goes all wrong. The reason i think is that, when I come back the currentpagenumber value at top is again becoming 1and startroeindex also becomes 1. Can u please let me know the way i can handle this?
I don't know your aspx page, but you need a way to send the previous page number. Otherwise, your script doesn't know what next means except 1+1. How do you change pages? Hyperlinks? If so, send the last page in a form field or query string.
first thing is that you are loading BindData on each and every post back, you must only call it on first time load.
Second thing, you are storing the in label, lblCurrentPage.Text = currentPageNumber.ToString(); So why dont you utilize the same and store it again on page_load event.
I have here provided the page_load event try this.
protected void Page_Load(object sender, EventArgs e)
{
currentPageNumber = Convert.ToInt32(lblCurrentPage.Text);
if(!IsPostback)
{
BindData();
}
}
please add default value for lblCurrentPage.Text to 1.