Check Email is register or not while register in Asp.net c#? - asp.net

I am trying to check whilist registrating. When an enterd email exists and then try to register it untill the registration is successfull but I don't want that.
protected void btnRegister_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand ("Select count(*) from tblUsers where Email = '" + txtEmail.Text + "' ", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
p.UserName = txtUsername.Text;
p.Email = txtEmail.Text;
p.DOB = Convert.ToDateTime(txtDob.Text);
p.Password = txtPass.Text;
p.InsertUser(p);
Response.Write("Registration Successfull..");
}
else {
Response.Write("This Email is Already Exist...!!");
}
}
else
{
Response.Write("Fail...");
}
}

Related

How to use local variable of Page_OnLoad method in OnClick event in asp.net C#

I am designing a website in which I need to update a table Company in my database through CompanyDetails page with respect to the auto increment field CompanyID which is being passed through Query string from previous page named Company and only one button is there for insert and update. So my problem is I am unable to get the value of Companyid of Page_OnLoad event in SaveButtonClick event.
Note: I have already tried Session and View state, IsPostBack but in Onclick event even their value are not being maintained and are updated to 0 or null.
Here is my code......(Please ignore my coding mistakes)
using System;
using System.Web.UI;
using System.Data;
using System.Data.SqlClient;
public partial class CompanyDetails : System.Web.UI.Page
{
int Companyid = 0;
string cmdName = null;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Companyid = Convert.ToInt32(Request.QueryString["CompanyID"]);
cmdName = Request.QueryString["CommandType"];
Session["something"] = Companyid;
}
if (cmdName == "Details")
{
BindTextBoxvalues();
}
}
protected void SaveButton_Click(object sender, EventArgs e)
{
string x = Session["something"].ToString();
try
{
if (SaveButton.Text == "Save")
{
SqlCommand cmd = new SqlCommand();
String mycon = "Data Source=.; Initial Catalog=something; Integrated Security=True";
SqlConnection con = new SqlConnection(mycon);
cmd = new SqlCommand("spInsertCompany", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#CompanyName", SqlDbType.VarChar).Value = Name.Text;
cmd.Parameters.Add("#CompanyCode", SqlDbType.VarChar).Value = CompanyCode.Text;
cmd.Parameters.Add("#LegalName", SqlDbType.VarChar).Value = LegalName.Text;
cmd.Parameters.Add("#TaxID", SqlDbType.Int).Value = TaxID.Text;
cmd.Parameters.Add("#BusinessPhone", SqlDbType.VarChar).Value = BusinessPhone.Text;
cmd.Parameters.Add("#Extension", SqlDbType.VarChar).Value = Extension.Text;
cmd.Parameters.Add("#FaxNumber", SqlDbType.VarChar).Value = FaxNumber.Text;
cmd.Parameters.Add("#Description", SqlDbType.VarChar).Value = Description.Value;
bool isstatus = IsActiveCheckBox.Checked;
cmd.Parameters.Add("#Status", SqlDbType.Int).Value = Convert.ToInt32(isstatus);
con.Open();
cmd.Connection = con;
cmd.ExecuteNonQuery();
Response.Write("<script language='javascript'>window.alert('Saved Successfully.');window.location='Company.aspx';</script>");
}
else if (SaveButton.Text == "Update")
{
SqlCommand cmd = new SqlCommand();
String mycon = "Data Source=.; Initial Catalog=something; Integrated Security=True";
SqlConnection con = new SqlConnection(mycon);
con.Open();
cmd = new SqlCommand("spUpdateCompany", con);
cmd.CommandType = CommandType.StoredProcedure;
int a = Convert.ToInt32(Companyid);
// I need the value here but it is being updated to zero here.
cmd.Parameters.Add("#CompanyID", SqlDbType.Int).Value = Companyid;
cmd.Parameters.Add("#CompanyName", SqlDbType.VarChar).Value = Name.Text;
cmd.Parameters.Add("#CompanyCode", SqlDbType.VarChar).Value = CompanyCode.Text;
cmd.Parameters.Add("#BusinessPhone", SqlDbType.VarChar).Value = BusinessPhone.Text;
cmd.Parameters.Add("#Extension", SqlDbType.VarChar).Value = Extension.Text;
cmd.Parameters.Add("#FaxNumber", SqlDbType.VarChar).Value = FaxNumber.Text;
cmd.Parameters.Add("#TaxID", SqlDbType.Int).Value = TaxID.Text;
cmd.Parameters.Add("#LegalName", SqlDbType.VarChar).Value = LegalName.Text;
cmd.ExecuteNonQuery();
cmd.Dispose();
con.Close();
Response.Write("<script language='javascript'>window.alert('Updated Successfully.');window.location='Company.aspx';</script>");
}
}
catch (SqlException ex)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Message",
"alert('Oops!! following error occured : " + ex.Message.ToString() + "');", true);
}
}
protected void CancelButton_Click(object sender, EventArgs e)
{
Response.Redirect("Company.aspx");
}
private void BindTextBoxvalues()
{
SaveButton.Text = "Update";
string constr = "Data Source=.; Initial Catalog=something; Integrated Security=True";
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand("select * from Company where CompanyID=" + Companyid, con);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
Name.Text = dt.Rows[0][1].ToString();
CompanyCode.Text = dt.Rows[0][2].ToString();
LegalName.Text = dt.Rows[0][15].ToString();
TaxID.Text = dt.Rows[0][14].ToString();
BusinessPhone.Text = dt.Rows[0][3].ToString();
Extension.Text = dt.Rows[0][13].ToString();
FaxNumber.Text = dt.Rows[0][12].ToString();
Description.Value = dt.Rows[0][4].ToString();
IsActiveCheckBox.Checked = Convert.ToBoolean(dt.Rows[0][11]);
}
}
Any values stored in local variables need to be read from Request on every postback.
So do following
int Companyid = 0;
string cmdName = null;
protected void Page_Load(object sender, EventArgs e)
{
Companyid = Convert.ToInt32(Request.QueryString["CompanyID"]);
cmdName = Request.QueryString["CommandType"];
if (!IsPostBack)
{
if (cmdName == "Details")// be sure about string case
{
BindTextBoxvalues();
}
}
}
Or make viewstate properties
If you want to have your property available on the PostBack, do not use !IsPostBack
protected void Page_Load(object sender, EventArgs e)
{
Companyid = Convert.ToInt32(Request.QueryString["CompanyID"]);
}

how to add confirmation in if statement

In my gridview I am inserting datas. If items repeated then it will show error message that "item repeated".But now I need to show "item repeated" message and another message that "you need to insert this data". If user press yes then that data need to be inserted.My current code only displays item repeated and cannot permit that data to enter. Here is my code
protected void AddNewCustomer(object sender, EventArgs e)
{
Control control = null;
if (GridView1.FooterRow != null)
{
control = GridView1.FooterRow;
}
else
{
control = GridView1.Controls[0].Controls[0];
}
string SlNo = (control.FindControl("txtSlNo") as TextBox).Text;
string Code = (control.FindControl("txtcode") as TextBox).Text;
string details = (control.FindControl("txtdetails") as TextBox).Text;
string Qty = (control.FindControl("txtqty") as TextBox).Text;
using (SqlConnection con = new SqlConnection("Data Source=xxxxx;Initial Catalog=xxxxx;User ID=xxxxx;Password=xxxxxx"))
{
using (SqlCommand cmd = new SqlCommand())
{
DataTable dt = new DataTable();
SqlDataAdapter da1;
da1 = new SqlDataAdapter("select code from Qtattemp where code='" + Code + "' ", con);
da1.Fill(dt);
if (dt.Rows.Count > 0)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(),
"alertMessage",
"alert('Item Repeated');", true);
}
else
{
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO [Qtattemp] VALUES(#Code,#details,#Qty,#SlNo)";
cmd.Parameters.AddWithValue("#SlNo", SlNo);
cmd.Parameters.AddWithValue("#Code", Code);
cmd.Parameters.AddWithValue("#details", details);
cmd.Parameters.AddWithValue("#Qty", Qty);
con.Open();
cmd.ExecuteNonQuery();
GridView1.DataBind();
BindData();
con.Close();
}
}
}
}
You need to handle it from code behind see the following link
http://www.aspsnippets.com/Articles/Server-Side-Code-Behind-Yes-No-Confirmation-Message-Box-in-ASPNet.aspx

how to display and update data in textbox of asp.net by using stored procedure?

i want to update user information .so first i want when user click on update button than all the field display with their values in text box so that user can able to edit his profile.
i got an error :Procedure or function 'updatefill' expects parameter '#email', which was not supplied.
please help me out from this error...
Thank you.
public partial class updateuser : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["cnstr"].ConnectionString);
SqlCommand cmd;
SqlDataAdapter da;
DataTable dt;
SqlDataReader dr;
string str1="";
protected void Page_Load(object sender, EventArgs e)
{
{
con.Open();
cmd = new SqlCommand("updatefill", con);
cmd.CommandType = CommandType.StoredProcedure;
da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds,"registr");
fname.Text = ds.Tables["registr"].Rows[0]["fname"].ToString();
lname.Text = ds.Tables["registr"].Rows[0]["lname"].ToString();
uid.Text = ds.Tables["registr"].Rows[0]["email"].ToString();
pwd.Text = ds.Tables["registr"].Rows[0]["password"].ToString();
pwd1.Text = ds.Tables["registr"].Rows[0]["confirmpassword"].ToString();
mbl.Text = ds.Tables["registr"].Rows[0]["mobile"].ToString();
con.Close();
}
}
protected void RadioButton1_CheckedChanged(object sender, EventArgs e)
{
if (RadioButton1.Checked)
{
str1 = "Male";
}
else if (RadioButton2.Checked)
{
str1 = "Female";
}
else
{
str1 = "please select gender";
}
}
protected void RadioButton2_CheckedChanged(object sender, EventArgs e)
{
}
protected void Button2_Click(object sender, EventArgs e)
{
con.Open();
cmd = new SqlCommand("update_user_details", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#fname", SqlDbType.VarChar).Value = fname.Text;
cmd.Parameters.Add("#lname", SqlDbType.VarChar).Value = lname.Text;
cmd.Parameters.Add("#email", SqlDbType.VarChar).Value = uid.Text;
cmd.Parameters.Add("#mobile", SqlDbType.VarChar).Value = mbl.Text;
cmd.Parameters.Add("#password", SqlDbType.VarChar).Value = pwd.Text;
cmd.Parameters.Add("#confirmpassword", SqlDbType.VarChar).Value = pwd1.Text;
cmd.Parameters.Add("#gender", str1);
dt = new DataTable();
da = new SqlDataAdapter(cmd);
da.Fill(dt);
int s = Convert.ToInt32(dt.Rows[0][0]);
if (s == 1)
{
errmsg.Text = "Update Successfull";
Response.Redirect("userhome.aspx");
}
else
{
errmsg.Text = "Update Faild";
con.Close();
}
ALTER PROCEDURE [dbo].[updatefill]
#email varchar(50)
AS
BEGIN
select * from registr where email=#email
END
Here is an example using the Reader:
String connStr = ConfigurationManager.ConnectionStrings["DB1"].ConnectionString;
String cmdStr = "SELECT [col2],[col3] FROM [Table1] WHERE [col1]=#col1;";
try
{
using (SqlConnection conn = new SqlConnection(connStr))
{
using (SqlCommand cmd = new SqlCommand(("updatefill", con);
{
cmd.CommandType = C0mmandType.StoredProcedure;
conn.Open();
using (SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
fname.Text = rdr[0];
lname.Text = rdr[1]
uid.Text = rdr[2]
pwd.Text = rdr[3]
pwd1.Text = rdr[4];
mbl.Text = rdr[5];
}
}
conn.Close();
cmd.Dispose();
conn.Dispose();
}
}
}
catch (Exception ex)
{
Label1.Text = ex.ToString();
}

Dynamically added checkboxs are not working in asp.net using c#?

i am adding multiple checkboxes in my asp.net page by doing this:
public static CheckBox[] chck;
on pageload:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
con.Open();
SqlCommand cmd = new SqlCommand("select count(CompanyName) from Stock_Company");
cmd.Connection = con;
comno = Convert.ToInt32(cmd.ExecuteScalar());
con.Close();
chck = new CheckBox[comno];
}
}
now i have a function which is generating the checkboxes :
public void generatecheckbox1()
{
con.Open();
SqlCommand cmd = new SqlCommand("select CompanyName from Stock_Company");
cmd.Connection = con;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
DataTable dt = ds.Tables[0];
con.Close();
for (int i = 0; i < dt.Rows.Count; i++)
{
chck[i] = new CheckBox();
chck[i].ID = "chck" + Convert.ToString(i);
chck[i].Text = dt.Rows[i]["CompanyName"].ToString();
pnlcom1.Controls.Add(chck[i]);
pnlcom1.Controls.Add(new LiteralControl("<br />"));
}
}
and i am calling this on a combobox event:
protected void ddluserwebser_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddluserwebser.SelectedItem.Text == "Custom")
{
generatecheckbox1();
}
}
as far as this all are working fine ... but in a button click i want to get the select checkbox's text which i am not getting
i made a function :
public string getbsecompany()
{
string companyname = "";
string bsetricker = "";
con.Open();
SqlCommand cmd = new SqlCommand("select CompanyName from Stock_Company");
cmd.Connection = con;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
DataTable dt = ds.Tables[0];
con.Close();
for (int i = 0; i < dt.Rows.Count; i++)
{
if (chck[i].Checked == true) **THE PROBLEM IS HERE**
{
companyname = chck[i].Text;
con.Open();
SqlCommand cmdd = new SqlCommand("select BSETickerCode from Stock_Company where CompanyName='" + companyname + "'");
cmdd.Connection = con;
bsetricker += bsetricker + "+" + cmdd.ExecuteScalar();
con.Close();
}
}
return bsetricker;
}
and i am calling it here:
protected void btnusersave_Click(object sender, EventArgs e)
{
string bsetricker = "";
bsetricker = getbsecompany();
}
the problem is i am not getting the checked box's text. when i am checking if (chck[i].Checked == true) i am gettin false and all checkboxes are checked.
What should i do now?
any help
The dynamic controls should added to page in On_Init() for each time if you want it display in page.
Else there's nothing you can get.
Plus, better not use a static value to contains checkBox List, it will cause problem when multi user access same page. You can save them in session or try this.Form.FindControls()

Trouble with "Last Login" Stored Procedure

Added a column "LastLogin" to a User table, however, it only stores the last login date the first time a user logs in to a password-protected page.
When the same user logs in a second time, the cell does not reflect his last login. Here is my stored procedure:
Here is my stored procedure:
ALTER PROCEDURE [dbo].[UpdateLastLogin] (
#intUserID int
)
-- Add the parameters for the stored procedure here
AS
SET NOCOUNT ON
UPDATE Users SET LastLogin = GETDATE() WHERE UserID = #intUserID
Here is my code:
public partial class Login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//SqlConnection oConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["XXXConnectionString"].ConnectionString);
//SqlCommand oCommand = new SqlCommand();
//oCommand.Connection = oConnection;
//oCommand.CommandText = "UpdateLastLogin";
//oCommand.CommandType = CommandType.StoredProcedure;
//oCommand.Parameters.Add(new SqlParameter("#intUserID", SqlDbType.NVarChar, 10)).Value = Int32.MaxValue;
//SqlDataAdapter adpt = new SqlDataAdapter(oCommand);
//DataSet ds = new DataSet();
//adpt.Fill(ds);
}
protected void loginButton_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["3GPSConnectionString"].ConnectionString);
con.Open();
string cmdStr = "Select count(*) from Users where UserName='" + userTextBox.Text + "'";
SqlCommand Checkuser = new SqlCommand(cmdStr, con);
int temp = Convert.ToInt32(Checkuser.ExecuteScalar().ToString());
if (temp == 1)
{
string cmdStr2 = "Select Password from Users where UserName='" + userTextBox.Text + "'";
SqlCommand pass = new SqlCommand(cmdStr2, con);
string password = pass.ExecuteScalar().ToString();
con.Close();
if (password == pwdTextBox.Text)
{
Session["New"] = userTextBox.Text;
Response.Redirect("/Protected/Default.aspx");
}
else
{
userCompareLbl.Visible = true;
userCompareLbl.Text = "Invalid Password!";
}
}
else
{
userCompareLbl.Visible = true;
userCompareLbl.Text = "Invalid Username!";
}
}
}

Resources