You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

从数据库填充ListBox双列仅显示FistName列的问题求助

嘿,我之前帮好几个开发者解决过一模一样的问题!你现在只能看到FirstName,大概率是因为ListBox默认只会显示单个文本项,而你没把FirstName和LastName组合成一个可显示的内容,或者读取数据/绑定的方式不对。我给你几个实用的解决办法:

1. 直接拼接字段(最快速的方案)

不管你是用DataReader还是DataSet,都可以在读取数据的时候把两个字段拼在一起,再给到ListBox:

// 举个ADO.NET DataReader的例子
List<string> fullNameList = new List<string>();
using (SqlDataReader reader = cmd.ExecuteReader())
{
    while (reader.Read())
    {
        // 确保你的查询里确实包含了FirstName和LastName
        string firstName = reader["FirstName"].ToString();
        string lastName = reader["LastName"].ToString();
        fullNameList.Add($"{firstName} {lastName}");
    }
}
yourListBox.DataSource = fullNameList;

或者更省事的,直接在SQL查询里拼接:

SELECT CONCAT(FirstName, ' ', LastName) AS FullName FROM YourTableName

然后绑定的时候直接取FullName字段就行。

2. 用实体类+DisplayMember(更规范的写法)

如果你的项目是用实体类来封装数据的,那可以给实体类加一个组合属性,或者重写ToString()方法:

方法A:添加组合属性

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    // 组合两个字段成一个属性
    public string FullName => $"{FirstName} {LastName}";
}

// 读取数据到实体集合
List<Person> people = new List<Person>();
using (SqlDataReader reader = cmd.ExecuteReader())
{
    while (reader.Read())
    {
        people.Add(new Person
        {
            FirstName = reader["FirstName"].ToString(),
            LastName = reader["LastName"].ToString()
        });
    }
}
// 绑定后指定显示FullName属性
yourListBox.DataSource = people;
yourListBox.DisplayMember = "FullName";

方法B:重写ToString()

如果你不想加额外属性,直接重写实体类的ToString(),ListBox会自动调用这个方法显示内容:

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public override string ToString()
    {
        return $"{FirstName} {LastName}";
    }
}

// 绑定的时候直接给实体集合就行,不用设置DisplayMember
yourListBox.DataSource = people;
3. 先排查基础问题

最后别忘了检查两个基础点:

  • 你的SQL查询语句是不是真的包含了LastName列?比如别写成SELECT FirstName FROM ...,要确保是SELECT FirstName, LastName FROM ...
  • 读取LastName的时候有没有拼写错误?比如数据库列名是LastName,你别写成Lastname或者lastName(有些数据库是大小写敏感的)

如果你其实想要真正的多列显示(比如左边FirstName右边LastName),那ListBox就做不到了,得换成ListView控件,设置为Details模式,然后添加两个列来绑定对应字段。

内容的提问来源于stack exchange,提问作者Maiko Fujimaru

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 08:20:40