简体   繁体   中英

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

In my ViewModel I have:

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:

<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. Also, I've tried to bind List and ObservableCollection to DataGrid but it doesn't work anyway.

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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