C# 从列表中检索第二列
我目前有一个类从sql数据库中检索记录并将其放入列表中。 该记录有多个列,我需要将所有记录中第二列的数据插入组合框 这是如何实现的,因为我找不到任何关于它的东西 处理器类别:C# 从列表中检索第二列,c#,C#,我目前有一个类从sql数据库中检索记录并将其放入列表中。 该记录有多个列,我需要将所有记录中第二列的数据插入组合框 这是如何实现的,因为我找不到任何关于它的东西 处理器类别: namespace RegForm { public class ClientProcessor { public List<Client> ClientList = new List<Client>(); public ClientProcess
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();
}
}
}
}
namespace RegForm
{
公共类客户端处理器
{
public List ClientList=新列表();
公共客户端处理器()
{
}
公共void LoadClients()
{
字符串sqlc=ConfigurationManager.ConnectionString[“sqlconn”].ConnectionString;
SqlConnection conn=新的SqlConnection(sqlc);
如果(连接状态!=连接状态打开)
{
conn.Open();
}
SqlCommand cmd=新的SqlCommand(“按CID从客户机订单中选择*”,conn);
尝试
{
SqlDataReader dr=cmd.ExecuteReader();
ClientList=新列表();
如果(哈斯罗博士)
{
while(dr.Read())
{
Client newClient=newClient();
newClient.ID=Convert.ToInt32(dr[“CID”]);
newClient.CNAME=dr[“CNAME”].ToString();
ClientList.Add(newClient);
}
}
}
捕获(例外情况除外)
{
控制台写入线(例如消息);
Console.WriteLine(例如InnerException);
}
if(conn.State==ConnectionState.Open)
{
康涅狄格州关闭();
}
}
}
}
假设您的数据在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
}
DataTable dt;
List lst=新列表()//将T替换为列类型
foreach(数据行r在dt.行中)
{
lst.Add(r[1]);//插入列表
combobox.Iteam.add(r[1]);//插入到combox
}
您可以试试这个
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;
}
public void BindData(列表)
{
//假设列表不为空
var dataFromSecondColumn=list.Select(l=>l.Name).ToList();
//重置您的代码。
comboBox1.DataSource=dataFromSecondColumn;
}
@SaiKalyanAkshinthala-告诉人们谷歌是没有建设性的。我们在这里不这样做。@Oded,实际上这类问题在SO中被问了很多次。所以,我这样说..我目前有一个类,它检索一个客户机并将其作为对象返回到列表中。该列表包含ID和名称。我需要从对象中检索第二个值。例如,我可以检索对象,但不能只显示名称。@SaiKalyanAkshinthala-你对谷歌说的。你没有说-这是以前问过的,请搜索该网站。您也没有提供重复问题的链接。您可以使用LINQ来完成此操作。我已经为它提供了一个示例代码。我想这对你会有用的。