Insert Query in registration form - c#

protected void Page_Load(object sender, EventArgs e)
{
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected void registerBtn_Click1(object sender, EventArgs e)
{
Page.Validate();
if (Page.IsValid)
{
outputlabel.Text = "Succesfully Registered";
myConnection.Open();
string query = "Insert into Users (FirstName,LastName,Gender,DateOfBirth,
Email_Id,Password) Values (#fn,#ln,#gen,#dob,#em,#pas)";
SqlCommand insertCommand = new SqlCommand(query, myConnection);
insertCommand.Parameters.AddWithValue("#fn", fname.Text);
insertCommand.Parameters.AddWithValue("#ln", lname.Text);
insertCommand.Parameters.AddWithValue("#gen", gender_dd.SelectedItem.Text);
insertCommand.Parameters.AddWithValue("#dob", date.Text);
insertCommand.Parameters.AddWithValue("#em", email.Text);
insertCommand.Parameters.AddWithValue("#pas", password.Text);
insertCommand.ExecuteNonQuery();
myConnection.Close();
}
}
}
}
Help me in this code..how can i edit this.If the same information is enter.Than code as show the message as already register.So no duplication in my database.

You need to run a SQL statement that checks if the user currently exists in the database before executing the INSERT into USERS statement.
So the code below will check if the user already exists based on the email address and password values they have supplied.
string userInvalid = "The username entered is invalid, please choose another."
string checkDatabase = "SELECT * FROM Users WHERE Email_Id = #em AND Password = #pas";
SqlCommand command = new SqlCommand(checkDatabase, myConnection);
command.Parameters.AddWithValue("#em", email.Text);
command.Parameters.AddWithValue("#pas", password.Text);
command.ExecuteNonQuery();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows) {
outputlabel.Text = userInvalid;
}
else
{
// execute your original SQL query
}

Related

Check if username is in the database using ASP.Net

I want to check if a username is already in the database. It comes along with my update statement. I have this code and I do not know where to put the select statement:
protected void btn_update_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(conn);
con.Open();
str = "update UserData set Password=#Password where UserName='" + txtUser.Text + "'";
com = new SqlCommand(str, con);
com.Parameters.Add(new SqlParameter("#Password", SqlDbType.VarChar));
com.Parameters["#Password"].Value = BusinessLayer.ShoppingCart.CreateSHAHash(txtPW.Text);
com.ExecuteNonQuery();
con.Close();
Label1.Visible = true;
Label1.Text = "Password changed Successfully!" ;
con.Close();
}
I want something like
"Select Username from Userdata Where Username = txtUser.Text"
You don't need a SELECT here. ExecuteNonQuery() returns the number of rows affected, which means that when it returns 0, there was no user with the given name in the database. If all went well, it should return 1.
Your code is vulnerable to SQL injection and leaks resources. Here's a better version:
protected void btn_update_Click(object sender, EventArgs e)
{
using(var con = new SqlConnection(conn))
{
con.Open();
var commandTest = "update UserData set Password=#Password where UserName=#Username";
using(var com = new SqlCommand(commandTest, con))
{
com.Parameters.AddWithValue("#Username", txtUser.Text);
com.Parameters.AddWithValue("#Password", BusinessLayer.ShoppingCart.CreateSHAHash(txtPW.Text));
if(com.ExecuteNonQuery() == 1)
{
Label1.Visible = true;
Label1.Text = "Password changed Successfully!" ;
}
}
}
}

how to search table through textbox?

I have piece of query that search database from text box.
My question is how can insert search result column by column to separated text box, I mean each column go to one textbox.
private void searchbtn_Click(object sender, EventArgs e)
{
SqlCeConnection con = new SqlCeConnection(#"Data Source=C:\Users\hry\Documents\Visual Studio 2010\Projects\Kargozini\Kargozini\khadamat.sdf");
try
{
con.Open();
string SearchQuerry = "SELECT ID, radif, Name, Type, Description, Price FROM Users WHERE ID = '"+searchtxt.Text+"'" ;
SqlCeCommand com = new SqlCeCommand(SearchQuerry,con);
com.ExecuteNonQuery();
con.Close();
}
catch (SqlCeException ex)
{
MessageBox.Show(ex.Message);
}
}
Try this :
private void searchbtn_Click(object sender, EventArgs e)
{
SqlConnection sql = new SqlConnection("Your String Connection");
SqlDataAdapter adapter = new SqlDataAdapter(#"Select Name, FileName From Table Where Name Like #Name", sql);
adapter.SelectCommand.Parameters.AddWithValue("#Name", string.Format("%{0}%", textBox1.Text));
}
I assume that, your search will return only one row.
You can use datareader to achieve that. I modified your function with below code:
private void searchbtn_Click(object sender, EventArgs e)
{
SqlCeConnection con = new SqlCeConnection(#"Data Source=C:\Users\hry\Documents\Visual Studio 2010\Projects\Kargozini\Kargozini\khadamat.sdf");
try
{
con.Open();
string SearchQuerry = "SELECT ID, radif, Name, Type, Description, Price FROM Users WHERE ID = '"+searchtxt.Text+"'" ;
SqlCeCommand com = new SqlCeCommand(SearchQuerry,con);
SqlCeDataReader sqlReader = com.ExecuteReader();
while (sqlReader.Read())
{
txtID.text = sqlReader.GetValue(0).ToString();
txtRadif.text = sqlReader.GetValue(1).ToString();
txtName.text = sqlReader.GetValue(2).ToString();
}
sqlReader.Close();
com.Dispose();
con.Close();
}
catch (SqlCeException ex)
{
MessageBox.Show(ex.Message);
}
}
Note: Your code is vulnerable to sqlinjection. Learn things to avoid it.

update asp.net text box

I have problem with updating data.
Sample:
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = GridView1.SelectedRow;
string id = row.Cells[1].Text;
Response.Redirect("edit.aspx?id="+id);
}
after this code transition to another page with update cmd.
protected void Page_Load(object sender, EventArgs e)
{
DataView dv = (DataView)SqlDataSource1.Select(DataSourceSelectArguments.Empty);
foreach (DataRowView drv in dv)
{
IDLBL.Text = drv["ID"].ToString();
Name.Text = drv["Name"].ToString();
SName.Text = drv["SecondName"].ToString();
Ocenka.Text = drv["Graduate"].ToString();
Klass.Text = drv["Class"].ToString();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ARM_TSPConnectionString"].ConnectionString);
con.Open();
string upd = "UPDATE Info SET Name=#Name, SecondName=#SecondName, Graduate=#Graduate, Class=#Class WHERE ID=#ID";
SqlCommand cmd = new SqlCommand(upd, con);
cmd.Parameters.AddWithValue("#ID", IDLBL.Text);
cmd.Parameters.AddWithValue("#SecondName", SName.Text);
cmd.Parameters.AddWithValue("#Graduate", Ocenka.SelectedValue);
cmd.Parameters.AddWithValue("#Class", Klass.SelectedValue);
cmd.Parameters.AddWithValue("#Name", Name.Text);
cmd.ExecuteNonQuery();
Response.Redirect("main.aspx");
}
I clicked button, and was redirected to main page. But nothing else, update doesn't work. :(
where do I have a problem?
I don't really know where is the problem, but for sure you need to refactor your update statement using the IDisposable capabilities of the connection object, it shoul look like this:
using (SqlConnection connection = new SqlConnection(
ConfigurationManager.ConnectionStrings["ARM_TSPConnectionString"].ConnectionString))
{
string upd = "UPDATE Info SET Name=#Name, SecondName=#SecondName, Graduate=#Graduate, Class=#Class WHERE ID=#ID";
SqlCommand cmd = new SqlCommand(upd, connection);
cmd.Parameters.AddWithValue("#ID", IDLBL.Text);
cmd.Parameters.AddWithValue("#SecondName", SName.Text);
cmd.Parameters.AddWithValue("#Graduate", Ocenka.SelectedValue);
cmd.Parameters.AddWithValue("#Class", Klass.SelectedValue);
cmd.Parameters.AddWithValue("#Name", Name.Text);
cmd.Connection.Open();
cmd.ExecuteNonQuery();
}
Your update sql query looks fine:
con.Open();
com.ExecuteNonQuery();
con.Close();
that is try using this function instead and debug it to see if there is a sql exception thrown.
protected void Button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ARM_TSPConnectionString"].ConnectionString);
string upd = "UPDATE Info SET Name=#Name, SecondName=#SecondName, Graduate=#Graduate, Class=#Class WHERE ID=#ID";
SqlCommand cmd = new SqlCommand(upd, con);
cmd.Parameters.AddWithValue("#ID", IDLBL.Text);
cmd.Parameters.AddWithValue("#SecondName", SName.Text);
cmd.Parameters.AddWithValue("#Graduate", Ocenka.SelectedValue);
cmd.Parameters.AddWithValue("#Class", Klass.SelectedValue);
cmd.Parameters.AddWithValue("#Name", Name.Text);
con.Open();
com.ExecuteNonQuery();
con.Close();
Response.Redirect("main.aspx");
}
catch (SqlException e)
{
}
}
UPDATE: Think I've realised why it's not working for you... you have a column called class... but class in sql server is a reserved keyword... so you must put square brackets around it ... like so
Edited the escaping (made a mistake as pointed out by Hans in the comment below)
string upd = "UPDATE Info SET Name=#Name, SecondName=#SecondName, Graduate=#Graduate, [Class]=#Class WHERE ID=#ID";
The problem was found.Just add in Page_Load if(!isPostBack)
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataView dv = (DataView)SqlDataSource1.Select(DataSourceSelectArguments.Empty);
foreach (DataRowView drv in dv)
{
IDLBL.Text = drv["ID"].ToString();
Name.Text = drv["Name"].ToString();
SName.Text = drv["SecondName"].ToString();
Ocenka.Text = drv["Graduate"].ToString();
Klass.Text = drv["Class"].ToString();
}
}
Now, all working good.

Table not update with new data

rIdThere are two text boxes in page. One is for UserId and the other one is for email. Both are retrieved data from table aspnet_membership and are set 'read-only'.
For email text box, it will change read-only = false. Then user get to enter a new email then hit button save. It should update the email in table with the new email but unfortunately no changes made. Can some one tell me what should I remove/add to make it works. Here is my code.
protected void Page_Load(object sender, EventArgs e)
{
string email = Membership.GetUser(User.Identity.Name).Email;
MembershipUser currentUser = Membership.GetUser();
string UserId = currentUser.ProviderUserKey.ToString();
TextBox2.Text = email;
TextBox3.Text = UserId;
}
protected void Button4_Click(object sender, EventArgs e)
{
TextBox2.ReadOnly = false;
}
protected void Button3_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString);
SqlCommand cmd = new SqlCommand("UPDATE aspnet_membership SET Email = #email WHERE UserName = #id1", conn);
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#email", TextBox2.Text);
cmd.Parameters.AddWithValue("#id1", TextBox3.Text);
}
I have refatored your code, now it should work
protected void Button3_Click(object sender, EventArgs e){
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString);
SqlCommand cmd = new SqlCommand("UPDATE aspnet_membership SET Email = #email WHERE UserName = #id1", conn);
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#email", TextBox2.Text);
cmd.Parameters.AddWithValue("#id1", TextBox3.Text);
try {
conn.Open();
cmd.ExecuteNonQuery();
}
catch(Exception ex){
throw ex;
}
finally{
conn.Close();
}
}
Look like you forgot to open connection
con.Open();
run command
cmd.ExecuteNonQuery();
and then close connection
con.Close();
You code is showing no signs of committing any data back to its Data Source.
You need a Data Adapter, and you need to set its Insert Command to the command above.
SQLDataAdapter adapt = new SQLataAdapter();
you then need to open a connection :-
conn.open();
adapt.UpdateCommand = cmd;
adapt.UpdateCommand.ExecuteNonQuery()
conn.close();
Hope This Helps.
You can try directly updating the user via Membership class in your button click event:
protected void Button3_Click(object sender, EventArgs e)
{
var memUser = Membership.GetUser(TextBox3.Text) //Fetch the user by user Id
memUser.Email = TextBox2.Text // Assign the new email address
Membership.UpdateUser(memUser) // update the user record.
}

Autocomplete for domain users

Is there any way to do autocomplete for domain users in .net?
Meaning, I want a textbox that when I will start and type Admin, it will complete it to \Administrator
Thanks.
Sure, you can hold a list of all valid domain account names and use an autocomplete (winforms example) with that data source.
Of course, this means you are exposing some sensitive information.
you can try like this for displaying domain user names ......
namespace AutoCompleteTextBox
{
public partial class frmAuto : Form
{
public string strConnection = ConfigurationManager.AppSettings["ConnString"];
AutoCompleteStringCollection namesCollection = new AutoCompleteStringCollection();
public frmAuto()
{
InitializeComponent();
}
private void frmAuto_Load(object sender, EventArgs e)
{
SqlDataReader dReader;
SqlConnection conn = new SqlConnection();
conn.ConnectionString = strConnection;
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText ="Select distinct [Name] from [Names]" + " order by [Name] asc";
conn.Open();
dReader = cmd.ExecuteReader();
if (dReader.HasRows == true)
{
while (dReader.Read())
namesCollection.Add(dReader["Name"].ToString());
}
else
{
MessageBox.Show("Data not found");
}
dReader.Close();
txtName.AutoCompleteMode = AutoCompleteMode.Suggest;
txtName.AutoCompleteSource = AutoCompleteSource.CustomSource;
txtName.AutoCompleteCustomSource = namesCollection;
}
private void btnCancel_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void btnOk_Click(object sender, EventArgs e)
{
MessageBox.Show(" this is autocomplete text box example");
}
}
}

Categories

Resources