0

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.

1
  • Because firstName and secondtName are not properties of a List object Commented Nov 29, 2015 at 0:42

1 Answer 1

2

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".

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot, it work. But at this moment only first column (firstName) set the data, second column was empty.
Because the binding the xaml is wrong, you have: Path=secondtName}" when it should be: Path=secondName}"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.