簡體   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