gpt4 book ai didi

c# - 从表单中提取填充方法

转载 作者:太空宇宙 更新时间:2023-11-03 18:57:33 25 4
gpt4 key购买 nike

我在 Windows 窗体上有一个组合框,我在其中填充了一个名称列表。目前我在 Form 类中有以下代码并且工作正常

    // This section opens a connection to the database, selects all the portfolio names that have an "in Use" value of 1, and then
// fills Combo Box 2 with the values.
SqlConnection myConnection = new SqlConnection(@"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename = ""C:\Users\Nick\Documents\Investments 4.mdf""; Integrated Security = True; Connect Timeout = 30");
myConnection.Open();
SqlCommand myCommand2 = new SqlCommand();
myCommand2.Connection = myConnection;
myCommand2.CommandText = "SELECT Portfolio_Name FROM Dbo.Name WHERE In_use = 1";
SqlDataReader myReader2 = myCommand2.ExecuteReader();
while (myReader2.Read())
{
comboBox2.Items.Add(myReader2[0]);
}
myConnection.Close();

我希望能够将其提取到一个单独的方法中,并将其放入一个单独的类中以用于通用实用方法。但是,我陷入了一个非常简单的问题。当我将代码放入类中时,我需要能够告诉它我要填充哪个组合框,但我不知道如何传递该信息。抱歉,如果答案显而易见,但我们将不胜感激。

谢谢!

最佳答案

好吧,要提取就提取:

// Let's extract a class: it should provide us standard cursors, 
// e.g. Protfolio Names
public static class MyData {
// Let's enumerate items returned
public static IEnumerable<string> PortfolioNames() {
// Wrap IDisposable into using
//TODO: move Connection String into a separated method/property
using (SqlConnection con = new SqlConnection(/*connection string here*/)) {
con.Open();

// Make sql readable
//DONE: when presenting something to user, sort it (order by) esp. strings
string sql =
@" select Portfolio_Name
from Dbo.Name
where In_use = 1
order by Portfolio_Name";

// Wrap IDisposable into using
using (SqlCommand q = new SqlCommand(sql, con)) {
// Wrap IDisposable into using
using (var reader = q.ExecuteReader()) {
while (reader.Read())
yield return Convert.ToString(reader[0]);
}
}
}
}
}

然后使用

// Adding items in one after one manner is often a bad idea:
// it makes UI repaint each time you add an item and cause blinking.
// Let's fill the ComboBox in one go via AddRange
comboBox2.Items.AddRange(MyData.PortfolioNames().ToArray());

关于c# - 从表单中提取填充方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41588612/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com