3

For some reason when I try to read in numbers from an Access database using this code, I just get blank entries in my data grid. I can read strings in fine. Anyone know why this may be? And yes, the actual data type for the unread entries in Access is a NUMBER.

        string strProvider = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Employees.mdb";
        string strSql = "SELECT * FROM tbl_employees";
        OleDbConnection con = new OleDbConnection(strProvider);
        OleDbCommand cmd = new OleDbCommand(strSql, con);
        con.Open();
        cmd.CommandType = CommandType.Text;
        OleDbDataReader dr = cmd.ExecuteReader();

        int columnCount = dr.FieldCount;

        for (int i = 0; i < columnCount; i++)
        {
            dgv.Columns.Add(dr.GetName(i).ToString(), dr.GetName(i).ToString());
        }

        string[] rowData = new string[columnCount];
        while (dr.Read())
        {
            for (int k = 0; k < columnCount; k++)
            {
                if (dr.GetFieldType(k).ToString() =="System.Int32")
                {
                    rowData[k] = dr.GetInt32(k).ToString();
                }

                if (dr.GetFieldType(k).ToString() == "System.String")
                {
                    rowData[k] = dr.GetString(k);
                }
            }

            dgv.Rows.Add(rowData);
        }

1 Answer 1

1

I suggest you try stepping through your code in the debugger so you can see what's happening. My first guess would be that your numeric fields aren't returned as Int32, perhaps they are floats or decimals instead.

If for some reason you can't step through it, try something like this:

            if (dr.GetFieldType(k).ToString() =="System.Int32")
            {
                rowData[k] = dr.GetInt32(k).ToString();
            }
            else if (dr.GetFieldType(k).ToString() == "System.String")
            {
                rowData[k] = dr.GetString(k);
            }
            else
            {
                rowData[k] = dr.GetFieldType(k).ToString();
            }

That will let you see what type of value is in the fields that didn't get displayed.

Sign up to request clarification or add additional context in comments.

3 Comments

I get a bunch of System.Single data types.
Great, @Emily, Single is a type of floating point number, so you just need to check for that type and convert it properly.
You might also want to read about data binding, @Emily. It's a much more powerful way of moving data from the database into your display.

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.