从List中检索第二列

时间:2012-02-06 11:02:37

标签: c#

我目前有一个类从sql数据库中检索记录并将它们放入列表中。 该记录有多列,我需要将所有记录中第二列的数据插入组合框。

这是如何实现的,因为我无法找到任何相关信息。

处理器类:

namespace RegForm
{
    public class ClientProcessor
    {
        public List<Client> ClientList = new List<Client>();


        public ClientProcessor()
        {
        }

        public void LoadClients()
        {
            string sqlc = ConfigurationManager.ConnectionStrings["sqlconn"].ConnectionString;
            SqlConnection conn = new SqlConnection(sqlc);

            if (conn.State != ConnectionState.Open)
            {
                conn.Open();
            }

            SqlCommand cmd = new SqlCommand("SELECT * FROM Clients ORDER BY CID", conn);
            try
            {
                SqlDataReader dr = cmd.ExecuteReader();

                ClientList = new List<Client>();

                if (dr.HasRows)
                {

                    while (dr.Read())
                    {
                        Client newClient = new Client();
                        newClient.ID = Convert.ToInt32(dr["CID"]);
                        newClient.CNAME= dr["CNAME"].ToString();

                        ClientList.Add(newClient);
                    }
                }
            }
            catch (Exception EX)
            {
                Console.WriteLine(EX.Message);
                Console.WriteLine(EX.InnerException);
            }

            if (conn.State == ConnectionState.Open)
            {
                conn.Close();
            }
        }
    }
}

2 个答案:

答案 0 :(得分:0)

假设您的数据在DataTable中,您可以执行以下操作:

DataTable dt;
List <T> lst = new List<T>();  //replace T with your column type
foreach (DataRow r in dt.Rows)
{
           lst.Add(r[1]); //insert to list
           combobox.Iteam.add(r[1]); //insert to combox 
}      

答案 1 :(得分:0)

你可以试试这个

class MyData
{
     public string Id{get;set;}
     public string Name{get;set;}
     //Other properties
}

内部绑定功能

public void BindData(List<MyData> list)
{
     //Assuming list is not null
     var dataFromSecondColumn = list.Select(l=>l.Name).ToList();
     //Reset of your code.  
     comboBox1.DataSource = dataFromSecondColumn;
}