Emily Johnson
Emily Johnson

Reputation: 73

Reading Entries From Access Database Into DataGridView Using C#

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);
        }

Upvotes: 3

Views: 691

Answers (1)

Don Kirkby
Don Kirkby

Reputation: 56230

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.

Upvotes: 1

Related Questions