ctrlaltdlt
ctrlaltdlt

Reputation: 9

WPF C# Datagrid update columns from SQL Server

I would like to get data from SQL Management Studio to datagrid but it doesn't work. First i have a class:

Person

Where i get the firstName and secondName.

class Person
{
    public string firstName { get; set; }
    public string secondName { get; set; }

}

I already created the button which is designed to make connection to database, use select query and refresh the database.

        string dbConnectionString = @"Data Source=Username\SQLEXPRESS;Initial Catalog=TestDatabase;Integrated Security=True";
        SqlConnection con = new SqlConnection(dbConnectionString);
        con.Open();
        string sqllogin = "SELECT firstName,secondName FROM TestDatabase.[dbo].[Persons]";
        SqlCommand cmd = new SqlCommand(sqllogin, con);
        SqlDataReader reader = cmd.ExecuteReader();


        List<Person> personList;
        personList = new List<Person>();

        while (reader.Read())
        {
            Person p = new Person();
            p.firstName = reader.GetString(0);
            p.secondName = reader.GetString(1);
            personList.Add(p);
        }

        dataGrid.DataContext = personList;

And XAML looks like this:

<DataGrid.Columns>
            <DataGridTextColumn Binding="{Binding Path=firstName}" Header="Name" MinWidth="100"/>
            <DataGridTextColumn Binding="{Binding Path=secondtName}" Header="Second Name" MinWidth="100"/>
</DataGrid.Columns>

And unfortunately it did not work. Any idea how i can fix this? At this moment when i click the button nothing happens.

Regards.

Upvotes: 0

Views: 439

Answers (1)

Raphael Teyssandier
Raphael Teyssandier

Reputation: 1777

you can try to switch your List into a ObservableCollection and change that

dataGrid.DataContext = personList;

to

dataGrid.ItemSource = personList;

Tell me if it's work, and after you can bind the itemsource of the Datagrid to not create a new ObservableCollection, and add directly your "Person".

Upvotes: 2

Related Questions