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

WPF C# 如何从txt文本文件读取内容添加到ComboList下拉列表

实现方案(按新手常用编程语言分类)

所有方案的核心逻辑都一致,只有2步:

  • 读取txt文件,逐行处理后存为字符串列表(每行对应下拉列表的1个选项)
  • 将列表内容批量添加到ComboList控件中

Python(Tkinter 图形界面,门槛最低)

前提准备

你的txt文件每行写1个下拉选项,示例option.txt内容:

选项1
选项2
选项3

完整可运行代码

import tkinter as tk
from tkinter import ttk

# 读取txt文件内容到列表
def read_txt(file_path):
    # 这里encoding根据你的txt实际编码改,乱码就换成gbk试试
    with open(file_path, 'r', encoding='utf-8') as f:
        # strip()去掉每行首尾的空格、换行符,过滤掉空行
        options = [line.strip() for line in f if line.strip()]
    return options

if __name__ == '__main__':
    root = tk.Tk()
    root.title("下拉列表示例")
    
    # 替换成你自己的txt文件实际路径
    option_list = read_txt("option.txt")
    
    # 创建下拉列表(Tkinter中ComboList对应控件名为Combobox)
    combobox = ttk.Combobox(root, values=option_list)
    # 可选:默认选中第一个选项
    if option_list:
        combobox.current(0)
    combobox.pack(padx=50, pady=30)
    
    root.mainloop()

如果你用PyQt/PySide,逻辑完全一致,读取到列表后调用QComboBox.addItems(option_list)即可。


C#(WinForm 方案)

完整代码

直接在窗口加载的事件中加入以下代码即可:

using System.IO;
using System.Text;
using System.Linq;

// 1. 读取txt文件内容,编码不对就换成Encoding.GetEncoding("gbk")
List<string> options = File.ReadAllLines("option.txt", Encoding.UTF8)
    .Where(line => !string.IsNullOrWhiteSpace(line))
    .ToList();

// 2. 批量添加到ComboBox控件
comboBox1.Items.AddRange(options.ToArray());
// 可选:默认选中第一个
if(comboBox1.Items.Count > 0) 
{
    comboBox1.SelectedIndex = 0;
}

如果是WPF项目,直接把读取到的options列表赋值给comboBox1.ItemsSource即可。


内容的提问来源于stack exchange,提问作者Mirko Tangredi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 10:48:02