[英]Combo Box Items are not Visible
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. 我已经编写了以下代码以在ComboBox中查看我的分数,并且全部在
populate()
方法中编写了该代码,并称其为窗体加载,但它显示了空的组合框。 Kindly tell me what's wrong it this code. 请告诉我这段代码有什么问题。
I have made a separate class for DatabaseConnection. 我为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. 当代码尝试在打开
OleDbConnection
之前创建OleDbCommand
对象时,我遇到了类似的问题。 Try doing the connection.Connection().Open();
尝试进行
connection.Connection().Open();
first, and then create the cmd
object. 首先,然后创建
cmd
对象。
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 catch语句来防止任何未处理的SQL异常。 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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.