C# 从表单中提取填充方法

C# 从表单中提取填充方法,c#,winforms,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 my

我在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();
我希望能够将其提取到一个单独的方法中,并将其放入一个单独的类中,用于通用实用程序方法。然而,我被困在一个非常简单的问题上。当我将代码放入一个类中时,我需要能够告诉它我要填充哪个combox框,而我不知道如何传递这些信息。如果答案显而易见,我很抱歉,但我们将非常感激您的帮助


谢谢

如果你想提取,那么提取:

// 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]);
        }
      }
    }
  }
}  

如果你想提取,那么提取:

// 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]);
        }
      }
    }
  }
}  

您可以使用助手类名组合进行数据访问。GetNames方法不需要ComboBox实例。这增加了在另一个上下文中重用该方法的机会

public static class Portfolio
{
    public static IList<string> GetNames()
    {
        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();
        var portfolioNames = new List<string>();
        while (myReader2.Read())
        {
            portfolioNames.Add(myReader2[0]);
        }
        myConnection.Close();
        return portfolioNames;
    }
 }

您可以使用助手类名组合进行数据访问。GetNames方法不需要ComboBox实例。这增加了在另一个上下文中重用该方法的机会

public static class Portfolio
{
    public static IList<string> GetNames()
    {
        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();
        var portfolioNames = new List<string>();
        while (myReader2.Read())
        {
            portfolioNames.Add(myReader2[0]);
        }
        myConnection.Close();
        return portfolioNames;
    }
 }
事情很简单:

public class MyUtility
{
    public static void FillComboBox(System.Windows.Forms.ComboBox comboBox)
    {
        //comboBox.Items.Clear(); //enable this line if required
        using (SqlConnection myConnection = new SqlConnection(@"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename = ""C:\Users\Nick\Documents\Investments 4.mdf""; Integrated Security = True; Connect Timeout = 30"))
        {
            myConnection.Open();
            using (SqlCommand myCommand2 = new SqlCommand())
            {
                myCommand2.Connection = myConnection;
                myCommand2.CommandText = "SELECT Portfolio_Name FROM Dbo.Name WHERE In_use = 1";
                using (SqlDataReader myReader2 = myCommand2.ExecuteReader())
                {
                    while (myReader2.Read())
                    {
                        comboBox.Items.Add(myReader2[0]);
                    }
                }
            }
            //myConnection.Close(); //not required inside using block
        }
    }
}
您可以使用其他方法获取连接字符串,例如从配置文件获取

用法非常简单,不需要额外的代码:

MyUtility.FillComboBox(comboBox2);
事情很简单:

public class MyUtility
{
    public static void FillComboBox(System.Windows.Forms.ComboBox comboBox)
    {
        //comboBox.Items.Clear(); //enable this line if required
        using (SqlConnection myConnection = new SqlConnection(@"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename = ""C:\Users\Nick\Documents\Investments 4.mdf""; Integrated Security = True; Connect Timeout = 30"))
        {
            myConnection.Open();
            using (SqlCommand myCommand2 = new SqlCommand())
            {
                myCommand2.Connection = myConnection;
                myCommand2.CommandText = "SELECT Portfolio_Name FROM Dbo.Name WHERE In_use = 1";
                using (SqlDataReader myReader2 = myCommand2.ExecuteReader())
                {
                    while (myReader2.Read())
                    {
                        comboBox.Items.Add(myReader2[0]);
                    }
                }
            }
            //myConnection.Close(); //not required inside using block
        }
    }
}
您可以使用其他方法获取连接字符串,例如从配置文件获取

用法非常简单,不需要额外的代码:

MyUtility.FillComboBox(comboBox2);

当您不知道应该使用什么组合框时,请在函数中使用组合框值作为参数。当您不知道应该使用什么组合框时,请在函数中使用组合框值作为参数。啊,是的,这是我的下一阶段!谢谢,是的,这是我的下一个阶段!谢谢你的连接。关闭;是冗余的-将使用SqlConnection myConnection=。。。{...} scope@DmitryBychenko是的,我只是从原始代码中留下了它,它是从问题中复制粘贴的。谢谢你的连接。关闭;是冗余的-将使用SqlConnection myConnection=。。。{...} scope@DmitryBychenko是的,我只是从原始代码中留下了它,它是从问题中复制粘贴的。谢谢