繁体   English   中英

组合框项目不可见

[英]Combo Box Items are not Visible

我已经编写了以下代码以在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();


    }

当代码尝试在打开OleDbConnection之前创建OleDbCommand对象时,我遇到了类似的问题。 尝试进行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();
        }
    }
}

在填充命令之前,应始终打开连接。 还可以使用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();
      }


}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM