I am designing a web form to insert data into sql database.I just want to check that email id which is unique already exists or not.
code:
protected void TextBox2_TextChanged(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(TextBox2.Text))
{
SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename='C:\\Users\\aayush\\Documents\\Visual Studio 2010\\WebSites\\JustDial\\App_Data\\Database.mdf';Integrated Security=True;User Instance=True");
con.Open();
SqlCommand cmd = new SqlCommand("select shop_email from shop where shop_email=#email", con);
cmd.Parameters.AddWithValue("#email", TextBox2.Text);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
Label1.Text = "email id already exists";
}
con.Close();
}
}
I tried above code but its not working i.e Label is not displaying anything.Any help will be thankful.
Problem : You are writing your code in TextBox_TextChanged Event handler so it would be invoked for everytime whenever there is a change in the TextBox and it would not give you the result untill unless you enter the complete Email-ID.
Solution 1: You need to write the above code in some Button Click Event handler as below:
protected void btnSearch_Click(object sender,EventArgs e)
{
//Write your code here
}
Solution 2: if you want to keep your code in the TextBox TextChanged Event handler but still want to identify the EmailID you can use LIKE operator instead of = operator
Try This:
SqlCommand cmd = new SqlCommand("select shop_email from shop
where shop_email LIKE #email", con);
cmd.Parameters.AddWithValue("#email", "'%"+TextBox2.Text +"%'"+);
try to add else statement in case if user/email does not exist
Also move this code to button click event or some other event. On Text Box text change event it will not return result.
using (var con = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename='C:\\Users\\aayush\\Documents\\Visual Studio 2010\\WebSites\\JustDial\\App_Data\\Database.mdf';Integrated Security=True;User Instance=True"))
using(var cmd = new SqlCommand("select 1 from shop where UserID=#UserID", con))
{
con.Open();
cmd.Parameters.AddWithValue("#UserID", TextBox2.Text);
using (var dr = cmd.ExecuteReader())
{
if (dr.HasRows)
{
Label1.Text = "userid already exists";
}
else
{
Label1.Text = "userid doesn't exists";
//Create new user
}
}
}
Related
So i've been looking around the google for the anwser to this found so many diffrenet anwsers but i do not quite understand them and dont really see the way to implement them even thoug i have tryed alot so my issue is basicly that my delete button only deletes from the datagridview and not the database itself i do have the gridview bound to my knowledge but this is the very first form app i make so im a bit puzzeld to what i am doing
private void buttonDel_Click(object sender, EventArgs e)
{///////////////////////////////////////////////////////issue is here
foreach (DataGridViewRow item in this.dataGridView1.SelectedRows)
{
dataGridView1.Rows.RemoveAt(item.Index);
}
//string del = "DELETE FROM Data WHERE RowID = #RowID";
}
using (SqlConnection Connection = new SqlConnection(Connectionstring))
{
string query = "insert into data(Navn, NummerPlade, KMKørt, dato)";
query += " values (#Navn, #NummerPlade, #KMKørt, #dato)";
Connection.Open();
SqlCommand cmd = new SqlCommand(query, Connection);
cmd.Parameters.AddWithValue("#Navn", textBox1.Text);
cmd.Parameters.AddWithValue("#NummerPlade", textBox8.Text);
cmd.Parameters.AddWithValue("#KMKørt", textBox6.Text);
cmd.Parameters.AddWithValue("#dato", textBox7.Text);
cmd.ExecuteNonQuery();
Connection.Close();
button4_Click(sender, e);
}
private void button4_Click(object sender, EventArgs e)
{
/// Connect / Update
using (SqlConnection Connection = new SqlConnection(Connectionstring))
{
Connection.Open();
SqlDataAdapter sqlDa = new SqlDataAdapter("SELECT * FROM Data", Connection);
DataTable data = new DataTable();
sqlDa.Fill(data);
dataGridView1.DataSource = data;
}
buttonConn.Hide();
}
I am trying to cancel a submit event if a response is true. I have a submission button in which i am wanting to check if the textbox is same as a value in the database. If it is then it will not allow the update to go ahead.
My C# code
protected void SubmitBtn_Click(object sender, EventArgs e)
{
if (IsPostBack)
{
SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\v11.0; AttachDbFilename=C:\Users\Donald\Documents\Visual Studio 2013\Projects\DesktopApplication\DesktopApplication\Student_CB.mdf ;Integrated Security=True");
conn.Open();
string sql = "Select count(*) from Student Where Student_Username=#username";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("username", usernameTxt.Text);
int temp = Convert.ToInt32(cmd.ExecuteScalar().ToString());
if (temp == 1)
{
Response.Write("User already exists");
}
conn.Close();
}
//SQL Connection and SQL for inserting a new student
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0; AttachDbFilename=C:\Users\Donald\Documents\Visual Studio 2013\Projects\DesktopApplication\DesktopApplication\Student_CB.mdf ;Integrated Security=True");
con.Open();
try
{
var sql = "INSERT INTO Student (Student_Username, Student_FName, Student_SName, Student_Email, Student_Password, Student_Status) " + "VALUES (#StudentName, #StudentFirstname, #StudentSurname, #StudentEmail, #StudentPassword, #StudentStatus);";
using (var cmd = new SqlCommand(sql, con))
{
cmd.Parameters.AddWithValue("#StudentName", usernameTxt.Text);
cmd.Parameters.AddWithValue("#StudentFirstname", firstnameTxt.Text);
cmd.Parameters.AddWithValue("#StudentSurname", surnameTxt.Text);
cmd.Parameters.AddWithValue("#StudentEmail", emailTxt.Text);
cmd.Parameters.AddWithValue("#StudentPassword", passwordTxt.Text);
cmd.Parameters.AddWithValue("#StudentStatus", statusTxt.Text);
cmd.ExecuteNonQuery();
}
greenPnl.Visible = true;
usernameTxt.Text = "";
firstnameTxt.Text = "";
surnameTxt.Text = "";
emailTxt.Text = "";
passwordTxt.Text = "";
retypePasswordTxt.Text = "";
}
catch (Exception ex)
{
Response.Write("Error:" + ex.ToString());
}
con.Close();
}
How can i call the eventArgs to cancel it? I know you cant simply e.cancel = true;
You can't "cancel" an event like that in ASP.NET. ASP.NET is a request/response platform - when you do something in the browser (click a link, submit a form, etc) - you send an entire request back to the server, and the browser waits for a response. That response will be rendered completely by the browser.
So some options are:
Continue with the ASP.NET lifecycle, completely rendering the page with whatever message you want to send back.
Use AJAX or some other mechanism to send a light request to the server before sending the entire request.
I made a login page were the employee type in employee email address and then their pin. The idea is for the program to check the email and the pin form a Access database to successfully log them in. This is the code that I used.
private void Validate(object sender, RoutedEventArgs e)
{
OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source = C:\\Users\\Baladi\\documents\\visual studio 2012\\Projects\\CalUnderFoot\\CalUnderFoot\\UserPerm.mdb");
OleDbCommand cmd = null;
OleDbDataReader dr = null;
string cmdStr = String.Format("select * from UserPermT where EmpEmail='{0}' and EmpPIN='{1}'", EmpEmailtxt.Text, EmpPINtxt.PasswordChar);
con.Open();
cmd = new OleDbCommand(cmdStr, con);
dr = cmd.ExecuteReader();
cmd.Dispose();
if (dr.Read() == true)
{
MessageBox.Show("success");
}
else
{
MessageBox.Show("fail");
}
dr.Dispose();
}
When I enter the wrong email and pin I get a message saying "fail" which is what it supposed to do. BUT, when I enter the right email and pin I still get the "fail" message. What am I missing??
And yes I know... I am not supposed to store passwords in databases and I will encrypt them in due time.
Thank you in advance
Try something like this:
private void Validate(object sender, RoutedEventArgs e)
{
using (OleDbConnection connection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source = C:\\Users\\Baladi\\documents\\visual studio 2012\\Projects\\CalUnderFoot\\CalUnderFoot\\UserPerm.mdb"))
{
OleDbCommand command = new OleDbCommand("select * from UserPermT where EmpEmail='"+EmpEmail.Text+"' and EmpPIN='"+EmpPIN.PasswordChar+"'", connection);
connection.Open();
OleDbDataReader dr= command.ExecuteReader();
if (dr.Read())
{
MessageBox.Show("success");
}
else
{
MessageBox.Show("fail");
}
dr.Close();
}
}
(from http://msdn.microsoft.com/en-us/library/979byfca.aspx)
I have a dataGridView in C# WinForms that display a custom items from a table in my database, and I have textbox and button for insert new rows in that table.
When I click on button, the Text of textbox will be inserted into table, I want after inserting, dataGridview can reload new item and display it too.
I use dataGridView1.Update(); and dataGridView1.Refresh(); and don't work.
I know that dataGridView can insert new items, but I want to insert items in my way.
it's my code on click event:
private void button1_Click(object sender, EventArgs e)
{
String connString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\bank.mdf;Integrated Security=True;User Instance=True";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand();
String cmdText = "insert into marja (ayatollah) values(#n)";
cmd.CommandText = cmdText;
cmd.Parameters.AddWithValue("#n", textBox4.Text);
cmd.Connection = conn;
conn.Open();
if (cmd.ExecuteNonQuery() > 0)
{
dataGridView1.DataSource = marjaBindingSource;
textBox4.Text = "آیت الله ";
}
else
MessageBox.Show("Error");
conn.Close();
}
You should try databinding, and possibly populate your data into ObservableCollection, you don't need manually call update, all is done automatically.
See also this post: Reloading Listbox content
Well you will have to use DataBind method to reload the datagridview.
Lets say DataGridView1 is the ID of your datagridview then use the below line of code after your Insert statement.
DataGridView1.DataSource = yourDataSource;
Refresh and Update methods wont server your purpose here.
All read this link for more information.
Can you alter your code to this:
private void button1_Click(object sender, EventArgs e)
{
int rowsAffected = 0;
String connString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\bank.mdf;Integrated Security=True;User Instance=True";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand();
String cmdText = "insert into marja (ayatollah) values(#n)";
cmd.CommandText = cmdText;
cmd.Parameters.AddWithValue("#n", textBox4.Text);
cmd.Connection = conn;
conn.Open();
rowsAffected = cmd.ExecuteNonQuery();
conn.Close();
if (rowsAffected > 0)
{
dataGridView1.DataSource = marjaBindingSource;
textBox4.Text = "آیت الله ";
}
else
{
MessageBox.Show("Error");
}
}
this.marjaTableAdapter.FillBy(this.bankDataSet10.marja);
it's my answer
I have a simple page like this. (EKLE = ADD, SİL = DELETE)
And my AVUKAT Table like this.
Simplify, When i choose first dropdown MUSTERI and second dropdown AVUKAT , add the database (getting HESAP (number) automaticly) or delete the database and gridview.
This is my code.
ADD Click
protected void Add_Click(object sender, EventArgs e)
{
string strConnectionString = ConfigurationManager.ConnectionStrings["SqlServerCstr"].ConnectionString;
SqlConnection myConnection = new SqlConnection(strConnectionString);
myConnection.Open();
string hesap = Label1.Text;
string musteriadi = DropDownList1.SelectedItem.Value;
string avukat = DropDownList2.SelectedItem.Value;
SqlCommand cmd = new SqlCommand("INSERT INTO AVUKAT VALUES (#MUSTERI, #AVUKAT, #HESAP)", myConnection);
cmd.Parameters.AddWithValue("#HESAP", hesap);
cmd.Parameters.AddWithValue("#MUSTERI", musteriadi);
cmd.Parameters.AddWithValue("#AVUKAT", avukat);
cmd.Connection = myConnection;
SqlDataReader dr = cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
/*GridView1.DataSource = dr;
GridView1.Visible = true;*/
Response.Redirect(Request.Url.ToString());
myConnection.Close();
}
DELETE Click
protected void Delete_Click(object sender, EventArgs e)
{
string strConnectionString = ConfigurationManager.ConnectionStrings["SqlServerCstr"].ConnectionString;
SqlConnection myConnection = new SqlConnection(strConnectionString);
myConnection.Open();
string hesap = Label1.Text;
string musteriadi = DropDownList1.SelectedItem.Value;
string avukat = DropDownList2.SelectedItem.Value;
SqlCommand cmd = new SqlCommand("DELETE FROM AVUKAT WHERE MUSTERI = #MUSTERI AND AVUKAT = #AVUKAT AND HESAP = #HESAP", myConnection);
cmd.Parameters.AddWithValue("#HESAP", hesap);
cmd.Parameters.AddWithValue("#MUSTERI", musteriadi);
cmd.Parameters.AddWithValue("#AVUKAT", avukat);
cmd.Connection = myConnection;
SqlDataReader dr = cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
/* GridView1.DataSource = dr;
GridView1.Visible = true;*/
Response.Redirect(Request.Url.ToString());
myConnection.Close();
}
My manager wants, delete process is so hard. Let's make easy. Because when i want to delete some data, i must choose two dropdownlist and then delete(Sil) button.
We should prefer that every row has a delete button. Then when we click the button. Then must be deleted gridview AND databse.
I found perfect example on the internet abuot what i want.
I think if we can do that, Sil(Delete) Button should be deleted.
How can we do that?
I think AutoDeleteButton don't work like this. Right? It just deleted from Gridview. Not Database. But i want deleting both (Gridview AND Database)
You need to ensure you calling the correct method.
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview_events.aspx
Clicking the button will run the "RowDeleting" method then "RowDeleted".
Edit - forgot to mention, once you've run your deleted method you'll need to rebind the gridview.
GridView1.DataBind()