"ExecuteScalar: Connection property has not been initialized." - c#

I'm new to c# and currently I have some problems when I'm running this program without debugging.
This is the login page for my project. I've create a service-based database and I want to connect to the data which is username and password in the table 'Table' which is in the database.
However, I've encountered an issue which is "ExecuteScalar: Connection property has not been initialized." when I'm running this code.
Can anyone help me with this?
private void button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=c:\users\hp\documents\visual studio 2015\Projects\PersonalFinancialSoftware\PersonalFinancialSoftware\Login.mdf;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "SELECT COUNT (*) FROM Table where UserID = #userid AND Password = #password";
cmd.Parameters.AddWithValue("#userid", textBox1.Text);
cmd.Parameters.AddWithValue("#password", textBox2.Text);
object result = cmd.ExecuteScalar();
conn.Open();
string useridlogin = Convert.ToString(result);
conn.Close();
if (useridlogin != " ")
{
Home_Page homepage = new Home_Page();
homepage.Show();
}
else
{
MessageBox.Show("Invalid ID or password, please try again!", "Info", MessageBoxButtons.OK);
}
}

I can see that you've executed the ExecuteScalar method before opening the SQL Database connection, resulting in error you're getting.
Open the connection before ExecuteScalar method, and you're done.
private void button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=c:\users\hp\documents\visual studio 2015\Projects\PersonalFinancialSoftware\PersonalFinancialSoftware\Login.mdf;Integrated Security=True");
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "SELECT COUNT (*) FROM Table where UserID = #userid AND Password = #password";
cmd.Parameters.AddWithValue("#userid", textBox1.Text);
cmd.Parameters.AddWithValue("#password", textBox2.Text);
object result = cmd.ExecuteScalar();
string useridlogin = Convert.ToString(result);
conn.Close();
if (useridlogin != " ")
{
Home_Page homepage = new Home_Page();
homepage.Show();
}
else
{
MessageBox.Show("Invalid ID or password, please try again!", "Info", MessageBoxButtons.OK);
}
}

You have open connection after ExecuteScalar thats you are getting error, You must open connection befor ExecuteScalar try this code
private void button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=c:\users\hp\documents\visual studio 2015\Projects\PersonalFinancialSoftware\PersonalFinancialSoftware\Login.mdf;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
conn.Open();
cmd.CommandText = "SELECT COUNT (*) FROM Table where UserID = #userid AND Password = #password";
cmd.Parameters.AddWithValue("#userid", textBox1.Text);
cmd.Parameters.AddWithValue("#password", textBox2.Text);
object result = cmd.ExecuteScalar();
string useridlogin = Convert.ToString(result);
conn.Close();
if (useridlogin != " ")
{
Home_Page homepage = new Home_Page();
homepage.Show();
}
else
{
MessageBox.Show("Invalid ID or password, please try again!", "Info", MessageBoxButtons.OK);
}
}
In your code SQL query find connection. But you have open it after ExecuteScalar so this is giving you an error.

Related

How do i store data in a service-based database?

I am trying to store the username and password inside a table called 'User' which is inside a service-based database.
Below is code of what i have tried.
private void Btn_register_Click(object sender, RoutedEventArgs e)
{
try
{
//Create the conection string and open the conn
SqlConnection conne = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=\\CUC-SRV-FS02\Studio-StuHome$\13mihailovs.m\Documents\IT_Unit4\IT_Unit4\ITUnit4.mdf;Integrated Security=True");
//Open the connection string
conne.Open();
//Get all the values from the text boxes etc and pass them over to the DB
string insertQuery = "insert into User(Username, Password) " +
"values(#Username, #Password)";
SqlCommand com = new SqlCommand(insertQuery, conne);
//Get values from the controls such as the text boxes and pass them over to the DB
com.Parameters.AddWithValue("#Username", txt_username.Text);
com.Parameters.AddWithValue("#Password", txt_password.Text);
//This actually executes the query with the given values above.
com.ExecuteNonQuery();
//Dispose the connection string once the data has been passed over the DB
conne.Close();
}
catch (Exception problem)
{
MessageBox.Show("error has occured");
}
}
currect way for insert into database in Ado.Net:
private readonly SqlConnection _con = new SqlConnection("Data Source=.;Initial
Catalog=dbPhoneBook;Integrated Security=True");
public string Add(string user , string pass)
{
string result = "";
SqlCommand cmd = new SqlCommand();
try
{
cmd.Connection = _con;
cmd.CommandText = "insert into tbl_login(user,pass)values(#user,#pass)";
cmd.Parameters.AddWithValue("#user", user);
cmd.Parameters.AddWithValue("#pass", pass);
if (_con.State != ConnectionState.Open)
{
_con.Open();
}
cmd.ExecuteNonQuery();
result = "Ok";
cmd.Dispose();
}
catch
{
cmd.Dispose();
result = "NOk";
}
return result;
}
Also check the following
Check out the web site https://www.connectionstrings.com/ link to the database.

C# update query

I am finding error of No value given for one or required parameter C# update query where ever i try to update my c# access data base here is the code...
hope somebody will be of my assistant..
private void updatebutton_Click(object sender, EventArgs e)
{
try
{
con.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
string query = "update Emplyeedata set [ID]='" + midbox.Text + "',[Name]='" + mnamebox.Text + "',[Deisgnation]='" + mdesbox.Text + "',[Leave]='" + mleavebox.Text + "'Where [Name]='"+mnamebox.Text+"'";
cmd.CommandText = query;
cmd.ExecuteNonQuery();
con.Close();
cb();
MessageBox.Show("Updated", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch
{
MessageBox.Show("Error", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
as a bit more improvement you can try like this, and if you can post the full error information.
private void updatebutton_Click()
{
using (OleDbConnection con = new OleDbConnection("Define your Connection String here"))
{
string query = #"UPDATE Emplyeedata
SET [id] = #ID
,[Name] = #Name
,[Deisgnation] = #Deisgnation
,[Leave] = #Leave
WHERE [Name] = #Name";
using (OleDbCommand cmd = new OleDbCommand(query, con) { CommandType = CommandType.Text })
{
cmd.Parameters.AddWithValue("#ID", midbox.Text);
cmd.Parameters.AddWithValue("#Name", mnamebox.Text);
cmd.Parameters.AddWithValue("#Deisgnation", mdesbox.Text);
cmd.Parameters.AddWithValue("#Leave", mleavebox.Text);
cmd.Parameters.AddWithValue("#Name", mnamebox.Text);
con.Open();
cmd.ExecuteNonQuery();
}
con.Close();
}
}
(this is a really unstructured way and please follow the SOLID Principle/s)

How to stop adding duplicate username into database table?

I'm working with ASP.Net web application project . in my Registration form the Username and the Email will be check if it's exist in the database or not. but my problem is if the username and the Email are exist the user can register normally and his data will be added in the database! how i can stop it from adding these data and forced the user to change the username or the Email if one of them is exist ! please any help ?
my .aspx.cs page :
protected void Button1_Click(object sender, EventArgs e)
{
byte[] License;
Stream s = FileUpload1.PostedFile.InputStream;
BinaryReader br = new BinaryReader(s);
License = br.ReadBytes((Int32)s.Length);
try
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyDatabase"].ConnectionString);
conn.Open();
string insertQuery = "insert into DeliveryMen (Name,Username,Password,Email,Phone,City,License) values (#name ,#username, #password, #email ,#phone ,#city,#License)";
SqlCommand com = new SqlCommand(insertQuery, conn);
com.Parameters.AddWithValue("#name", TextBoxName.Text);
com.Parameters.AddWithValue("#username", TextBoxUsername.Text);
com.Parameters.AddWithValue("#password", TextBoxPassword.Text);
com.Parameters.AddWithValue("#email", TextBoxEmail.Text);
com.Parameters.AddWithValue("#phone", TextBoxPhone.Text);
com.Parameters.AddWithValue("#city", DropDownList1.SelectedItem.ToString());
com.Parameters.AddWithValue("#License", License);
com.ExecuteNonQuery();
Response.Write("DONE");
conn.Close();
}
catch (Exception ex)
{ Response.Write("Error:" + ex.ToString()); }
}
protected void TextBoxUsername_TextChanged(object sender, EventArgs e)
{ // to check if the Username if exist
if (!string.IsNullOrEmpty(TextBoxUsername.Text))
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyDatabase"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("select * from DeliveryMen where Username=#Username", con);
cmd.Parameters.AddWithValue("#Username", TextBoxUsername.Text);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
checkusername.Visible = true;
imgstatus.ImageUrl = "NotAvailable.jpg";
lblStatus.Text = "UserName Already Taken";
System.Threading.Thread.Sleep(2000);
}
else
{
checkusername.Visible = true;
imgstatus.ImageUrl = "Icon_Available.gif";
lblStatus.Text = "UserName Available";
System.Threading.Thread.Sleep(2000);
}
}
else
{
checkusername.Visible = false;
}
}
protected void TextBoxEmail_TextChanged(object sender, EventArgs e)
{ // to check if the Email if exist
if (!string.IsNullOrEmpty(TextBoxEmail.Text))
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyDatabase"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("select * from DeliveryMen where Email=#email", con);
cmd.Parameters.AddWithValue("#Email", TextBoxEmail.Text);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
Div1.Visible = true;
Image1.ImageUrl = "NotAvailable.jpg";
Label2.Text = "the Email Already Taken";
System.Threading.Thread.Sleep(2000);
}
else
{
Div1.Visible = true;
Image1.ImageUrl = "Icon_Available.gif";
Label2.Text = "the Email Available";
System.Threading.Thread.Sleep(2000);
}
}
else
{
Div1.Visible = false;
}
}
Set unique constraints on your Username and email columns, your sql insert will throw an exception and you can handle that and notifiy the client accordingly.
See https://msdn.microsoft.com/en-GB/library/ms190024.aspx
use an insert stored procedure instead of inline insert query and in stored procedure before insert check where this username email id exist or not.
if (not exists(select 1 from DeliveryMen where Username= #Username and Email=#Email))
begin
insert into DeliveryMen (Name,Username,Password,Email,Phone,City,License) values (#name ,#username, #password, #email ,#phone ,#city,#License)
end
The primary key needs to be set in the database itself.
Suppose 'username' is your primary key and therefore unique. Then you can check whether it already exists in the database or not as follows:
private void button2_Click(object sender, EventArgs e
{
conn.Open();
com.Connection = conn;
sql = "SELECT COUNT(*) FROM lapusers WHERE [username] = #username";
com.CommandText = sql;
com.Parameters.Clear();
com.Parameters.AddWithValue("#username", userlapbox.Text);
int numRecords = (int)com.ExecuteScalar();
if (numrecords == 0)
{
sql = "INSERT INTO lapusers([username],[fillingcode],[branch],[department],[agency])VALUES(#username,#fillingcode,#branch,#department,#agency)";
com.CommandText = sql;
com.Parameters.Clear();
com.Parameters.AddWithValue("#username", userlapbox.Text);
com.Parameters.AddWithValue("#fillingcode", userfilllapbox.Text);
com.Parameters.AddWithValue("#branch", comboBox2.Text);
com.Parameters.AddWithValue("#department", comboBox1.Text);
com.Parameters.AddWithValue("#agency", comboBox3.Text);
com.ExecuteNonQuery();
MessageBox.Show("Created Successfully ..");
}
else
{
MessageBox.Show("A record with a user name of {0} already exists", userlapbox.Text);
}
conn.Close();
}

inserting textbox value to sql server using c#

I need to add a text box value to SQL Server database table. Below is my code:
private void button1_Click(object sender, EventArgs e)
{
string str = "Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\timetablesystem.mdf;Integrated Security=True;User Instance=True";
SqlConnection con = new SqlConnection(str);
string qry = "insert into SubjectMaster (SubjectName) values (#TxtSubjectName)";
con.Open();
SqlCommand cmd = new SqlCommand(qry, con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#TxtSubjectName", TxtSubjectName.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Added Successfully!!");
con.Close();
}
But, data should not add in table... please help me...
thanks for ur help...
Try debugging your query first if it works i think your connection with your db isnt working.
string str = "Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\timetablesystem.mdf;Integrated Security=True;User Instance=True";
is there supposed to be this '.' after data source Data Source=.\\SQLEXPRESS
try this and tell me what is the message information content
private void button1_Click(object sender, EventArgs e)
{
string str = "Server=.\SQLEXPRESS;Database=TestDB;Trusted_Connection=True;";
using( SqlConnection con = new SqlConnection(str)){
try{
con.Open();
string qry = "insert into SubjectMaster (SubjectName) values (#TxtSubjectName)";
SqlCommand cmd = new SqlCommand(qry, con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#TxtSubjectName", TxtSubjectName.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Added Successfully!!");
}
catch{
MessageBox.Show("connection is failed!!");
}
}
}
try this
SqlConnection con = new SqlConnection(#"Data Source=SL-20\SQLEXPRESS;Initial Catalog=TestDB;User ID=sa;Password=sl123;");
string query = " insert into name(name)values('" + TextboxTest.Text + "')";
con.Open();
SqlCommand cmd = new SqlCommand(query, con);
cmd.ExecuteNonQuery();
con.Close();

Unable to update data into SQL table

I got a question. When I put this 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;**
}
My data will not be saved to the database.
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString);
SqlCommand cmd = new SqlCommand("UPDATE aspnet_Membership SET Email = #email WHERE UserId = #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();
}
But when I removed
**TextBox2.Text = email;
TextBox3.Text = UserId;**
The data will be saved into database using above code. Can someone tell me why? Thanks in advance.
Given you never execute the command I can't explain it.
Add
cmd.ExecuteNonQuery();
To the end of your click method
Because you are setting the values in your page load event, they are overwriting the changed values in the controls when your button on postback. Wrap your page load code with a
if (!Page.IsPostback)
{
string email = Membership.GetUser(User.Identity.Name).Email;
MembershipUser currentUser = Membership.GetUser();
string UserId = currentUser.ProviderUserKey.ToString();
TextBox2.Text = email;
TextBox3.Text = UserId;
}
You are never executing your SQL so I'm very surprised that your DB is updating at all.
Take a look at the ExecuteNonQuery method. With your current query you are creating a SQLCommand and then never running the SQL.
Try the following
cmd.Connection = conn;
cmd.Connection.Open()
after you assign it and then
cmd.ExecuteNonQuery();

Categories