We help IT Professionals succeed at work.
Get Started

How to create function that returns a single value and single row from MS Access Database in C#

138 Views
Last Modified: 2019-12-22
Hello,

I would like to create a function and return a single value like an example;

public static string GetValueFromAccess(string uniqueID) {....}

As in example i'd like to get result "DF556-33446" when i set uniquID = 30075

I'm trying to edit this code to implement it but didn't succeeded.

        private void AccessReader_Click(object sender, RoutedEventArgs e)
        {
            string connetionString = null;
            OleDbConnection cnn;
            OleDbCommand cmd;
            string sql = null;

            connetionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Mode=Read;Data Source=E:\SampleData\ASampleDatabase.accdb";

            sql = "Select Count(*) from [Asset Items]";

            cnn = new OleDbConnection(connetionString);
            try
            {
                cnn.Open();
                MessageBox.Show("Connection Opened ");
                cmd = new OleDbCommand(sql, cnn);
                cmd.ExecuteNonQuery();
                cmd.Dispose();
                cnn.Close();
                MessageBox.Show(" ExecuteNonQuery in OleDbConnection executed !! :");
            }
            catch (Exception ex)
            {
                MessageBox.Show("Can not open connection ! " + ex.ToString());
            }
        }

Open in new window


You can find sample database on attachment also.

AccessExample.pngASampleDatabase.accdb
Comment
Watch Question
Retired
CERTIFIED EXPERT
Distinguished Expert 2017
Commented:
This problem has been solved!
Unlock 1 Answer and 3 Comments.
See Answer
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE