Question

I am trying to get a value from Access database to textBox in WPF. Table name is Member and the column name is MemberID.I tried the following code, but I get an exception at line "OleDbDataReader reader = command.ExecuteReader();"

The exception is: An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll. Additional information: Data type mismatch in criteria expression.

The code:

    private void showInfoBtn_Click(object sender, RoutedEventArgs e)
    {
        int index = 1;

        string connection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:/Users/Cvenko/Desktop/Library.accdb";

        using (OleDbConnection conn = new OleDbConnection(connection))
        {
            conn.Open();

            OleDbCommand command = new OleDbCommand("SELECT FirstName FROM Member WHERE MemberID = '" + index + "'", conn);
            OleDbDataAdapter adapter = new OleDbDataAdapter(command);

            AddMember m = new AddMember();
            m.Show();

            OleDbDataReader reader = command.ExecuteReader();
            if (reader.HasRows)
            {
                reader.Read();
                m.nameTxt.Text = reader.GetString(1);
            }

            conn.Close();
            command.Dispose();
            adapter.Dispose();
        }
    }
Was it helpful?

Solution

I very much doubt that MemberID is text, so you should not use quotes:

"SELECT FirstName FROM Member WHERE MemberID = " + index 

OTHER TIPS

As @Remou already stated, MemberID is a number and not a string. You are using string concatenation in order to build your SQL command. Use command parameters instead. Also, since you only return the first column of the first row, you can use ExecuteScalar. It does exactly this.

var command = new OleDbCommand("SELECT FirstName FROM Member WHERE MemberID = @1", 
                               conn);
command.Parameters.AddWithValue("@1", index);
string firstName = (string)command.ExecuteScalar();
if (fistName != null) {
    m.nameTxt.Text = firstName;
}

Advantages of command parameters are:

  • You don't have to care about the right representation of values as a literal in SQL. (Especially practical for date values.)

  • Prevents SQL injection attacks.

  • Usually easier to read than lengthy string concatenations

  • You don't have to care about texts containing SQL string delimiters, line breaks and other oddities.

--

You are also creating a OleDbDataAdapter that is never used. Drop it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top