简体   繁体   English

将数据从SQL数据库添加到DataGrid C#WPF MVVM

[英]Add data from SQL database to DataGrid C# WPF MVVM

I'm connecting to SQL Database and trying to fill DataGrid with received DataTable, but DataGrid is empty 我正在连接到SQL数据库,并尝试用接收到的DataTable填充DataGrid,但是DataGrid为空

In my ViewModel I have: 在我的ViewModel中,我有:

DataTable: 数据表:

private DataTable _myData;
public DataTable MyData 
{  get => _myData;
   set=> UpdateValue(value, ref _myData);
}

Connecting Method: 连接方式:

var connStr = new StringBuilder();
            const string agentsQuery =
                "select CONCAT(users.last_name, ' ', users.first_name) as Agent from users where users.valid_id = 1 group by users.id";

            connStr.AppendFormat("server={0};user={1};database=otrs;password={2}",
                Connect.IP,
                Connect.User,
                Connect.Password);

            Connect.Connection = new MySqlConnection(connStr.ToString());
            Connect.Connection.Open();

           using (var sqlCom = new MySqlCommand(agentsQuery,  Connect.Connection))
                {
                    sqlCom.ExecuteNonQuery();
                    var dataAdapter = new MySqlDataAdapter(sqlCom);
                    dataAdapter.Fill(_myData);

                }

XAML Code: XAML代码:

<DataGrid ItemsSource="{Binding Path=MyData}"
          AutoGenerateColumns="True">
</DataGrid>

Connection is working. 连接正常。 I've tried to load data to List and bind to ComboBox and everything is OK. 我试图将数据加载到列表并绑定到ComboBox,一切正常。 Also, I've tried to bind List and ObservableCollection to DataGrid but it doesn't work anyway. 另外,我尝试将List和ObservableCollection绑定到DataGrid,但无论如何都无法正常工作。

using (var sqlCom = new MySqlCommand(agentsQuery, Connect.Connection))
                {
                    sqlCom.ExecuteNonQuery();
                    var dt = new DataTable();
                    var dataAdapter = new MySqlDataAdapter(sqlCom);
                    dataAdapter.Fill(dt);
                    MyData = dt;

                }

That's worked! 没问题!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM