MrMalith
MrMalith

Reputation: 1372

c# winform program connect to a sql database

I'm creating a c# winform and I need to connect with a sql database which I already have, basically I need to registered users to log into the program using username and password..but I'm having issues with the db connection I guess, there's a run time error "connection property has not been initialized!"

I used this same connection string and my login form connected successfully..

String cs = (@"Data Source=DESKTOP-3BDK76K\SQLEXPRESS;Initial Catalog=FurnitureOrdering;Integrated Security=True");
private void button1_Click(object sender, EventArgs e)
       {

        try
        {

            SqlConnection myConnection = default(SqlConnection);
            myConnection = new SqlConnection(cs);

            SqlCommand myCommand = default(SqlCommand);

            myCommand = new SqlCommand("SELECT username,password FROM Register WHERE username= @username AND password = @password");

            SqlParameter uName = new SqlParameter("@username", SqlDbType.VarChar);
            SqlParameter uPassword = new SqlParameter("@password", SqlDbType.VarChar);

            uName.Value = txtUserName.Text;
            uPassword.Value = txtPassword.Text;

            myCommand.Parameters.Add(uName);
            myCommand.Parameters.Add(uPassword);


            myConnection.Open();

            SqlDataReader myReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);

            if (myReader.Read() == true)
            {
                MessageBox.Show("Successfully logged-in"+ txtUserName.Text);
                this.Hide();

                Main_UI ss2 = new Main_UI();
                ss2.Show();
            }
            else
            {
                MessageBox.Show("Login failed!");

                txtUserName.Clear();
                txtPassword.Clear();
            }
            if (myConnection.State == ConnectionState.Open)
            {
                myConnection.Dispose();
            }
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

error message

"connection property has not been initialized!"

Upvotes: 0

Views: 781

Answers (1)

Parsa Karami
Parsa Karami

Reputation: 722

You must set connection property of your SqlCommand object.

myCommand.Connection = myConnection;

Upvotes: 2

Related Questions