0
if (txtUsername.Text != "")
        {
            string q = "insert into info(Username) values ('" + txtUsername.Text.ToString() + "')";
            dosomething(q);
            txtUsername.Text = "";
        }
        else
        {
            MessageBox.Show("Please Complete the neccessary information");
        }
        if (txtPassword.Text != "")
        {
            string a = "insert into info(Password) values ('" + txtPassword.Text.ToString() + "')";
            dosomething(a);
            txtUsername.Text = "";

        }
        else
        {
            MessageBox.Show("Please Complete the neccessary information");
        }

private void dosomething(String q)
{
    try
    {
        cn.Open();
        cmd.CommandText = q;
        cmd.ExecuteNonQuery();
        cn.Close();

    }
    catch (Exception e)
    {
        cn.Close();
        MessageBox.Show(e.Message.ToString());
    }
}

Every time I run this it always show that error. I dont know how to fix it. The code should record the data i put in a textbox to ms access database. plz helpp

4
  • 3
    where have you define cn & how did you pass the connectionstring to it? Commented Sep 30, 2015 at 8:01
  • please include the code of the connection string in your post Commented Sep 30, 2015 at 8:04
  • cn = connection object, which you would pass the connectionstring to... read up codeproject.com/Articles/4416/… Commented Sep 30, 2015 at 8:04
  • I know that this is a beginner's code, but there are just so many things wrong with that... Commented Sep 30, 2015 at 8:04

1 Answer 1

2

Presumably, you've initialized cn somewhere by doing something like

cn = new SqlConnection();

You need to pass the connection string for the database to the constructor:

cn = new SqlConnection("your connection string here");

or set it sometime later, before you connect:

cn.ConnectionString = "your connection string here";
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.