在我的VB.net应用程序中,我有5个列表框,我正在填写表单加载。但我有丑陋的解决方案,因为对于每个列表框我都有一些FillItUp函数,它打开连接,从数据库获取数据,然后填充我的列表框。问题是我在表单加载时触发了这五次。
这是我的代码:
Public Sub FillListboxesColors()
Try
sqL = "SELECT * FROM Colors"
ConnDB()
cmd = New OleDbCommand(sqL, conn)
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection)
Do While dr.Read = True
chkColor.Items.Add(dr.Item("color"))
Loop
Catch ex As Exception
MsgBox(ex.Message)
Finally
cmd.Dispose()
conn.Close()
End Try
End Sub
我对每个CheckedListBox都有这种确切的情况。 所以问题是 - 有一种方法可以在一个程序中填充所有列表框。所以我只打开了一次与数据库的连接。
像这样......但我知道这对AccessDB来说是不可能的。
cmd.CommandText = "SELECT * FROM Colors; SELECT * FROM Paper"
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection)
Do While dr.Read = True
chkColor.Items.Add(dr.Item("color"))
chkPaper.Items.Add(dr.Item("paper_type"))
Loop
我要求一些帮助代码。 TY。
答案 0 :(得分:0)
以下C#代码显示了一种只使用一个数据库连接填充列表框的方法:
using (var con = new OleDbConnection())
{
con.ConnectionString = myConnectionString;
con.Open();
using (OleDbCommand cmd = new OleDbCommand("SELECT [Color] FROM [Colors]", con))
{
using (OleDbDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
Console.WriteLine(String.Format("This is where you would .Add '{0}' to the .Items for chkColor.", rdr["Color"]));
}
Console.WriteLine();
}
}
using (OleDbCommand cmd = new OleDbCommand("SELECT [Size] FROM [Sizes]", con))
{
using (OleDbDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
Console.WriteLine(String.Format("This is where you would .Add '{0}' to the .Items for chkSize.", rdr["Size"]));
}
Console.WriteLine();
}
}
con.Close();
}
程序输出为:
This is where you would .Add 'Red' to the .Items for chkColor.
This is where you would .Add 'Green' to the .Items for chkColor.
This is where you would .Add 'Blue' to the .Items for chkColor.
This is where you would .Add 'Small' to the .Items for chkSize.
This is where you would .Add 'Medium' to the .Items for chkSize.
This is where you would .Add 'Large' to the .Items for chkSize.
您只需用Console.WriteLine
语句替换while
循环中的chkColor.Items.Add
语句(并将C#语法调整为VB.NET语法)。