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

标签 c# winforms

我在 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/

相关文章:

c# - 如何测试 8 :00 PM is valid prior to 12:00 AM?

c# - 用字符串填充 ListView

winforms - WinForms .Net 3.5 中的 CheckedListBox 中没有 DisplayMember

c# - 如何在数据库表中查找连接的组合框中所选项目的索引

c# - 返回引用类型的方法返回引用还是克隆副本?

C# 2022 IDE - 没有关于代码样式或变量命名的警告?

c# - OnValidateIdentity ASP.NET Identity 如何工作

c# - 无法将值 NULL 插入列 'EmpId'

winforms - 在 Winforms for Vista 中为 MessageBox.Show(...) 格式化消息的最佳实践

c# - 如何在 winform 中以 XML 方式显示 Xml 数据?