I'm new to this site and also to programming. I am currently creating an inventory system via a point of sale. It uses modal and non-modal forms. My problem is tho, I'm working on the change password dialog which has to be connected to the database in order to overwrite the password field. The database i used is microsoft sql server management studio express. Here is what I have so far with the necessary comments. Please note that on the 'design' form, I have a combobox which is bounded to the database. Where did I go wrong?
private void ChangePwdButton_Click(object sender, EventArgs e)
{
SqlConnection sqlconn = new SqlConnection();
sqlconn.ConnectionString = #"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Gerald- dean Martin\Documents\SQL Server Management Studio Express\Projects\BodyMates.mdf;Integrated Security=True;User Instance=True";
sqlconn.Open();
string oldpwd = txtOldPwd.Text;
string newpwd = txtNewPwd.Text;
string confirmNewPwd = txtConfirmNewPwd.Text;
string sqlquery = "UPDATE [Employee] SET Pwd=#newpass where EmployeeCode=#empcode";
SqlCommand cmd = new SqlCommand(sqlquery, sqlconn);
cmd.Parameters.AddWithValue("#newpass", txtConfirmNewPwd.Text);
cmd.Parameters.AddWithValue("#empcode", comboEmpCode.SelectedValue);
//cmd.Parameters.AddWithValue("#pwd", txtNewPwd.Text);
cmd.Connection = sqlconn;
cmd.ExecuteNonQuery();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if(txtOldPwd.Text == dr["pwd"].ToString() && (txtNewPwd.Text == txtConfirmNewPwd.Text))
{
if (comboEmpCode.SelectedIndex == 0)
{
string query = "UPDATE [Employee] SET Pwd = '" + txtConfirmNewPwd.Text + "'";
}
}
// if ((txtNewPwd.Text == dr["newpwd"].ToString()) & (txtConfirmNewPwd.Text == (dr["confirmNewPwd"].ToString()))) { }
}
// MessageBox.Show("Password was changed Successfully!", "Password Change", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
You can use ExecuteNonQuery like cmd.ExecuteNonQuery(); It returns int value. Use it like this;
int i = cmd.ExecuteNonQuery();
And also ExecuteReader() works like this;
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(String.Format("{0}", reader[0]));
}
You can read returning data's column. Like first column reader[0], second column reader[1] etc.
But before all this information, if you are new to programming, you can find a lot of book proposal and useful informations on Stackoverflow. Check these articles;
What is the single most influential book every programmer should read?
https://stackoverflow.com/questions/477748/what-are-the-best-c-sharp-books
https://stackoverflow.com/questions/2018/best-book-for-a-new-database-developer
Related
I'm trying to check if the username is already in use in C# database and it's giving me this error
SqlConnection cn = new SqlConnection(#"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename = C:\Users\admin\Desktop\241 Project sem 1 2020-2021\Online Banking - ITIS 241 project group 9\UobBankDatabase.mdf; Integrated Security = True; Connect Timeout = 30");
cn.Open();
SqlCommand cmd = new SqlCommand("select * from LoginTable where user_name='" + textBox1.Text + "'", cn);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
dr.Close();
MessageBox.Show("Username Already exist please try another ", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
dr.Close();
}
and yes I'm a newbie
Use this:
SqlCommand cmd = new SqlCommand("Select count(*) from LoginTable where user_name='" + textBox1.Text + "'", cn);
Then:
var dr = cmd.ExecuteScalar();
if (dr != null)
{
//Exists
}
else
{
//Unique username
}
Google it please:
Since the error is SqlException: Invalid object name 'Movie' , that
means the table named 'Movie' has not created or the Database you are
referring has not created. To see if the Database or table 'Movie' has
created, open SQL Server Object Explorer and check the Database name
is the same as in appsettings. json
And Please tell us at what line do you get that?
Is that this line =>if (dr.Read())
Let's extract method for the check:
private static bool NameAvailable(string name) {
//DONE: wrap IDisposable into using
using (SqlConnection cn = new SqlConnection("Connection String Here")) {
cn.Open();
//DONE: keep Sql readable
//DONE: make Sql parametrize
//DONE: select 1 - we don't want entire record but a fact that record exists
string sql =
#"select 1
form LoginTable
where user_name = #prm_user_name";
using (var cmd = new SqlCommand(sql, cn)) {
cmd.Parameters.Add("#prm_user_name", SqlDbType.VarChar).Value = name;
using (var dr = cmd.ExecuteReader()) {
return !dr.Read(); // Not available if we can read at least one record
}
}
}
}
Then you can put
if (!NameAvailable(textBox1)) {
// Let's be nice and put keyboard focus on the wrong input
if (textBox1.CanFocus)
textBox1.Focus();
MessageBox.Show("Username Already exist please try another ",
"Error",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
some changes only.it is better to get what is the error than a temporary solution so print your query first and run it in the sqlserver . also add initial catalog instead of attacjing mdf files its way better in my opinion.
<connectionStrings>
<add name="stringname" connectionString="Data Source=mssql;Initial Catalog=databasename; Persist Security Info=True;User ID=sa;Password=*****;MultipleActiveResultSets=true" providerName="System.Data.SqlClient"/>
</connectionStrings>
using a connection string instead also
SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["stringname"].ConnectionString);
cn.Open();
string query = "select * from LoginTable where user_name='" + textBox1.Text.ToString() + "'";
SqlCommand cmd = new SqlCommand(query, cn);
SqlDataReader dr = cmd.ExecuteReader();
//print query if error and comment the execute reader section when printing the query to know the error Respone.Write(query);
if (!dr.HasRows)
{
// ur code to insert InsertItemPosition values
}
else
{
//show username exist
}
dr.Close();
Try this:
string conString = ConfigurationManager.ConnectionStrings["YourConnection"].ConnectionString;
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlCommand cmd = new SqlCommand("SELECT COUNT(UserName) as UserCount FROM LoginTable WHERE user_name = #user_name", con))
{
con.Open();
cmd.Parameters.AddWithValue("#user_name", TextBox1.Text);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if (dr.HasRows)
{
if(Convert.ToInt32(dr["UserCount"].ToString()) >= 1)
{
// Exists
}
else
{
// Doesn't Exist
}
}
}
con.Close();
}
}
I'm creating a visual studio project that uses a local SQL server database as a data source, which is up and running correctly.
I need to create a login form for the project.
The form has a username textbox and a password textbox which the user will populate with their details, and then hit the 'login' button, which needs to execute the select sql statement.
Any references on how to do this?
The code I have tried is below.
It's throwing a NullReferenceException at the line that says "SqlDataReader dr = cmd.ExecuteReader();"
How do I Solve the nullreferenceexception?
Thank you!
private void button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=MARKO-PC\\SQLEXPRESS;Initial Catalog=IS2B_G8_FundMeDB;Integrated Security=True";
con.Open();
String sql = "Select * from APPLICANT where applicant_ID_passport =#user AND password = #password";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.Add(new SqlParameter("#user", txtUserName.Text));
cmd.Parameters.Add(new SqlParameter("#password", txtPassword.Text));
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows == true)
{
MessageBox.Show("Login Successful");
}
else
{
MessageBox.Show("Login Failed");
}
}
catch (SqlException sqle)
{
MessageBox.Show("Sql Exception");
}
}
Try this
string struser = txtUserName.Text;
string strpwd = txtPassword.Text;
String sql = "Select * from APPLICANT where applicant_ID_passport=" + struser + " AND password = " + strpwd +"";
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader dr = cmd.ExecuteReader();
You need to do some research into using ADO.Net, specifically the SQLCommand class.
However I would refrain from using inline sql statements like above as this opens you up to SQL injection. Rather use paramaterised queries, stored procedures or LINQ to SQL.
I am trying to insert data into a database that I have that has a table called EmployeeInfo
The user is prompted to enter a last name and select a department ID (displayed to the user as either marketing or development) The column ID automatically increments.
Here is my Code behind
protected void SubmitEmployee_Click(object sender, EventArgs e)
{
var submittedEmployeeName = TextBox1.Text;
var submittedDepartment = selectEmployeeDepartment.Text;
if (submittedEmployeeName == "")
{
nameError.Text = "*Last name cannot be blank";
}
else
{
System.Data.SqlClient.SqlConnection sqlConnection1 =
new System.Data.SqlClient.SqlConnection("ConnString");
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "INSERT INTO EmployeeInfo (LastName, DepartmentID ) VALUES ('" + submittedEmployeeName + "', " + submittedDepartment + ")";
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
cmd.ExecuteNonQuery();
sqlConnection1.Close();
}
}
The error I'm recieving is 'Arguement exception was unhandled by user code'
Here is a picture of it.
As requested. More details
If I had enough reputation, I would rather post this as a reply, but it might actually be the solution.
The reason why it stops there is because you are not providing a legit SqlConnection, since your input is: "ConnString", which is just that text.
The connection string should look something like:
const string MyConnectionString = "SERVER=localhost;DATABASE=DbName;UID=userID;PWD=userPW;"
Which in your case should end up like:
System.Data.SqlClient.SqlConnection sqlConnection1 = new System.Data.SqlClient.SqlConnection(MyConnectionString);
Besides that, you should build your connections like following:
using (SqlConnection con = new SqlConnection(MyConnectionString)) {
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = xxxxxx; // Your query to the database
cmd.Connection = con;
cmd.Connection.Open();
cmd.ExecuteNonQuery();
}
}
This will do the closing for you and it also makes it easier for you to nestle connections. I did a project recently and did the connection your way, which ended up not working when I wanted to do more than one execute in one function. Just important to make a new command for each execute.
I am developing this website in ASP.NET and using C#. I am Getting the error that :Use of unassigned variable usn. The database is also not empty.
My code is:
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection();
SqlCommand cm = new SqlCommand();
SqlDataReader dr;
cn.ConnectionString = #"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Vijaylaxmi\Desktop\TrainReserveold\App_Data\Database.mdf;Integrated Security=True;User Instance=True";
cn.Open();
cm.Connection = cn;
String usn;
cm.CommandText = "Select UserName from User where UserName='" + TextBox1.Text + "'";
dr = cm.ExecuteReader();
while (dr.Read())
{
usn = dr.GetString(0);
}
if (String.Compare(usn, TextBox1.Text) != 0)
{
Response.Write("Invalid user name... try again");
TextBox1.Text = "";
TextBox2.Text = "";
TextBox1.Focus();
}
Response.Write("user valid now");
}
Several problems I see here. In specific response to your question, you want to replace this:
dr = cm.ExecuteReader();
while(dr.Read())
{
usn = dr.GetString(0);
}
with this:
usn = cm.ExecuteScalar().ToString();
Be sure to check for DBNull first, just in case.
More generally, you want to
a) Parameterize your SQL (or, better, use a stored proc) instead of using raw input. This will protect you from SQL Injection attacks.
b) Not include your connection string directly in code. Put it in a config file. Most certainly don't post it on the internet.
assing the usn string up top as
string usn = string.empty; then go from there
//create a Stored Procedure and put your Select Statement in there.. to avoid Sql Injection
cmd.CommandText = "name of your stored proc";
cmd.CommandType = System.Data.CommandType.StoredProcedure;
I would also read my sql connectiong string from a web.config or app.config depending on the type of application you are running.
change your cm.CommandText = "Select UserName from User where UserName=
to
cm.CommandText = string.Format("Select UserName from User where UserName= '{0}'",Textbox1.Text);
private void d_Load(object sender, EventArgs e)
{
string connstring = #"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\it155.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
SqlConnection conn = new SqlConnection(connstring);
try
{
conn.Open();
string snumber = txtSnumber.Text;
SqlCommand get = new SqlCommand(#"Select from IStudent where SNumber ='" + txtSnumber.Text + "'", conn);
}
catch (Exception)
{
}
}
given the start of the code which is written above, what i plan to do is to be able to log in using id number datatype varchar(11) in the sql database which was to be entered in the txtSnumber but aside that i cant figure out how to check whether the id number entered is correct or not and if it is correct, the information corresponding to that id number enetered is supposed to show in the their corresponding textboxes. please help me, thanks
Your sql statement is prone to SQL Injection. Is terrible practice to concatenate SQL like this. Instead do something like this:
string snumber = txtSnumber.Text;
SqlCommand get = new SqlCommand(#"Select from IStudent where SNumber =#User", conn);
get.Parameters.AddWithValue("#User",snumber);
Now, in order to check whether the record was found or not, you do this:
using(IDataReader reader = get.ExecuteReader())
{
if (reader.HasRows)
{
//information correct. Do something
}
}
You can check it by using a DataReader()
SqlCommand get = new SqlCommand(#"Select from IStudent where SNumber ='" + txtSnumber.Text + "'", conn);
SqlDataReader myReader = get.ExecuteReader();
if (myReader.HasRows)
{
MessageBox.Show("ID is valid");
while (myReader.Read())
//Do something here
}
else
MessageBox.Show("Given ID is Invalid.");
EDIT:
While calling ExecuteReader() method you put the following argument inside it, so that when ever you close the connection the datareader also automatically closes.
SqlDataReader myReader = get.ExecuteReader(CommandBehavior.CloseConnection);