Hi I am new to using Microsoft Access as a database for Visual Studio (previously I used SQL Server) so I am unsure how to go about the usual tasks such as accessing the database. At the minute I am trying to write code to check if a username already exists in the database, if it does I want it to inform the user, if not it should go ahead and insert the record. So far after researching this is the code I have came up with

 String regUser = txtNewUser.Text;

            OleDbConnection conn;
            OleDbCommand cmd;

            using (conn = new OleDbConnection(ConfigurationManager.ConnectionStrings["ProjectDatabaseConnectionString"].ConnectionString))
            {
                using (cmd = conn.CreateCommand())
                {
                    cmd.CommandText = "SELECT * FROM Users WHERE username=?";
                    cmd.Parameters.AddWithValue("username", txtNewUser.Text);

                    object username = cmd.ExecuteScalar();
                    if (username == null)
                    {

                    }
                }

however I am unsure if this is correct. Can anyone help or even direct me to a tutorial on using Access as the database.

Thanks in advance

You need to correct the parameter name and SELECT statement. You can either use ? or @paramName.

cmd.CommandText = "SELECT username FROM Users WHERE username=@username";
cmd.Parameters.AddWithValue("@username", txtNewUser.Text);

PS: ExecuteScalar() returns value from 1st column and 1st row.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.