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.

Edit

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

其他提示

You should always open the connection before you populate your command. Also use a try catch statement to prevent any unhandled SQL exceptions. Try it this way:

    public void populate()
    {
       DatabaseConnection connection = new DatabaseConnection();
       try{
       connection.Connection().Open();
       OleDbCommand cmd = new OleDbCommand;
       cmd.Connection = connection.Connection();
       cmd.ComandText = "Select score from Info"
       OleDbDataReader reader = cmd.ExecuteReader();

           while (reader.Read())
           {   
                comboBox1.Items.Add(reader[0].ToString());
           }
        }
       catch(SqlException e){



      }
      finaly{
        connection.Connection().Close();
      }


}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top