1

我已经编写了以下代码来在 ComboBox 中查看我的分数,我将这一切都写在populate()方法中,我称之为表单加载,但它显示了空的组合框。请告诉我这段代码有什么问题。

我为 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();


    }
4

2 回答 2

1

当代码在打开之前尝试创建OleDbCommand对象时,我看到了类似的问题OleDbConnection。尝试做第connection.Connection().Open();一个,然后创建cmd对象。

编辑

以下是对我有用的确切代码:

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();
        }
    }
}
于 2013-04-27T12:12:51.867 回答
1

在填充命令之前,您应该始终打开连接。还可以使用 try catch 语句来防止任何未处理的 SQL 异常。试试这种方式:

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


}
于 2013-04-27T13:11:18.880 回答