Visual Studio C#: How to check a value against Access table?

VAer-4038 776 Reputation points
2020-12-31T04:12:25.427+00:00
 private void btnConnect_Click(object sender, EventArgs e)
        {
            //I have an Access file, file path: C:\Users\QR\Documents\UserDatabase.accdb ; file password is: Pa$$word123;
            //The access file has a table called User, and the table has a field called UserID (Employee UserID is unique, it is work PC, employee userID is same as Environment.UserName)
            //If Environment.UserName is not in the table, then it is first time that the person uses this application, and it will loop to another Registration form.

        }

I will need to write code to check if Environment.UserName is not in the table , how do write it? In general, I have no idea how to connect Visual Studio to Access database.

Thanks.

Developer technologies | Visual Studio | Other
Developer technologies | Visual Studio | Other

A family of Microsoft suites of integrated development tools for building applications for Windows, the web, mobile devices and many other platforms. Miscellaneous topics that do not fit into specific categories.

0 comments No comments

Answer accepted by question author
Dylan Zhu-MSFT 6,436 Reputation points
2020-12-31T08:48:06.313+00:00

Hi VAer,

You can use System.Data.OleDb Namespace to read and write data from access database. And please refer to this sample:

        private void button1_Click(object sender, EventArgs e)  
        {  
            if (isInDataBase("aa"))  
            {  
                MessageBox.Show("yes");  
            }  
            else  
            {  
                MessageBox.Show("No");  
            }  
        }  

        public bool isInDataBase(string username)  
        {  
            string connString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\data.accdb;Jet OLEDB:Database Password=Pa$$word123;";  
            using (OleDbConnection connection = new OleDbConnection(connString))  
            {  
                OleDbCommand command = new OleDbCommand("SELECT username FROM [Table]", connection);  
                connection.Open();  
                OleDbDataReader reader = command.ExecuteReader();  

                while (reader.Read())  
                {  
                    if(reader[0].ToString() == username) return true;  
                }  
            }  
            return false;  
        }  

Best Regards, Dylan

If the answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our * *documentation* to enable e-mail notifications if you want to receive the related email notification for this thread.**

Was this answer helpful?


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.