c# - 在 WPF 的组合框中显示 MySQL 数据库的列?我只显示 'System.Data.DataRowView'

标签 c# mysql database wpf data-binding

我正在尝试获取表列中的值以填充组合框的选项。每当我尝试时,组合框都会填充正确数量的选项,但选项不是列的值,而是全部“System.Data.DataRowView”。

XAML

<ComboBox x:Name="ComboBox_1" HorizontalAlignment="Left" Margin="124,23,0,0" VerticalAlignment="Top" Width="95" Height="42" ItemsSource="{Binding}"/>

C#

public MainWindow()
{
    InitializeComponent();
    string connectionString = "SERVER=localhost;DATABASE=dbname; UID=myPC;Password=myPW;";

    MySqlConnection connection = new MySqlConnection(connectionString);

    MySqlCommand cmd = new MySqlCommand("Select columnname from tablename", connection);
    connection.Open();


    DataTable dt = new DataTable();
    dt.Load(cmd.ExecuteReader());
    connection.Close();

    ComboBox_1.DataContext = dt;

}

最佳答案

您应该像这样设置 DisplayMemberPath。

<ComboBox DisplayMemberPath="YourColumnName"/>

并将 ComboBox 的 ItemsSource 设置为 dt.DefaultView,如下所示。

ComboBox_1.ItemsSource = dt.DefaultView;

您只能在组合框中显示一列。如果要显示所有列,可以使用 DataGrid 或为 ComboBox 定义 ItemTemplate。

关于c# - 在 WPF 的组合框中显示 MySQL 数据库的列?我只显示 'System.Data.DataRowView',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55867507/

相关文章:

database - 如何在 rails 中使用选项卡

sql - Rails 使用 dependent destroy 和 dependent nullify 时

c# - 如何在 C# 中遗漏 ZedGraph 线图中的点

c# - 非泛型类型中的泛型方法

mysql - SELECT all 如果参数为 null 否则返回特定项目 laravel

mysql - Yii - MySQL CREATE VIEW 何时被调用?

mysql数据库结构

c# - ReSharper 5 禁用解析 View

c# - 正则表达式捕获组

Mysql基于int的列字符串