I have written the following code to view my score in ComboBox, and I write this all in populate()
method, and I call it form load, but it shows empty combo box. Kindly tell me what's wrong it this code.
I have made a separate class for DatabaseConnection.
public void populate()
{
DatabaseConnection connection = new DatabaseConnection();
OleDbCommand cmd = new OleDbCommand("Select score from Info", connection.Connection());
connection.Connection().Open();
OleDbDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
comboBox1.Items.Add(reader[0].ToString());
}
connection.Connection().Close();
}
I have seen similar problems when the code tries to create the OleDbCommand
object before the OleDbConnection
has been opened. Try doing the connection.Connection().Open();
first, and then create the cmd
object.
The following is the exact code that works for me:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace comboTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
var con = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\kirmani\Documents\Score.accdb");
con.Open();
var cmd = new OleDbCommand("SELECT Score FROM Info", con);
OleDbDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
comboBox1.Items.Add(rdr[0].ToString());
}
con.Close();
}
}
}