开发者

C# winforms adding items from a combobox to from a seperate class

What I have is my combobox on Form1.cs [Design], and i created a separate class called SQLOperations to operate my SQL stuff, how do I pass to the combobox?

 public static void SQLServerPull()
    {
        string server = "p";
        string database = "IBpiopalog";
        string security = "SSPI";
        string sql = "select server from dbo.ServerList";
        SqlConnection con = new SqlConnection("Data Source=" + server + ";Initial Catalog=" + database + ";Integrated Security=" + security);
        con.Open();
        SqlCommand cmd = new SqlCommand(sql, con);
        SqlDataReader dr = cmd.ExecuteReader();
        while(dr.Read())
        {
//this below doesnt work because it can't find the comboBox
            comboBox1.Items.Add(dr[0].ToString());
//the rest of the 开发者_StackOverflowcode works fine
        }
        con.Close();
    }


Instead of coupling your UI and data, why don't you simply return a set of data from your "SQLServerPull" method? The UI can use that raw data in any way it sees fit, for example, filling a ComboBox.


Why not do this

public static System.Collections.Generic.List<string> SQLServerPull()
    {
        System.Collections.Generic.List<string> Items = new System.Collections.Generic.List<string>();
        string server = "p";
        string database = "IBpiopalog";
        string security = "SSPI";
        string sql = "select server from dbo.ServerList";
        using(SqlConnection con = new SqlConnection("Data Source=" + server + ";Initial Catalog=" + database + ";Integrated Security=" + security))
        {
            con.Open();
            SqlCommand cmd = new SqlCommand(sql, con);
            SqlDataReader dr = cmd.ExecuteReader();
            while(dr.Read())
            {
                //Add the items to the list.
                Items.Add(dr[0].ToString());
                //this below doesnt work because it can't find the comboBox             
                //comboBox1.Items.Add(dr[0].ToString());
                //the rest of the code works fine
            }
        }
        //Return the list of items.
        return Items;
    }

Or return a DataTable

public static System.Data.DataTable SQLServerPull()
    {
        System.Data.DataTable dt = new System.Data.DataTable();
        string server = "p";
        string database = "IBpiopalog";
        string security = "SSPI";
        string sql = "select server from dbo.ServerList";
        using(SqlConnection con = new SqlConnection("Data Source=" + server + ";Initial Catalog=" + database + ";Integrated Security=" + security))
        {
            con.Open();
            using(SqlCommand cmd = new SqlCommand(sql, con))
            {
                using(SqlDataReader dr = cmd.ExecuteReader())
                {
                    dt.Load(dr);
                }
            }
        }
        return dt;
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜