user13657
user13657

Reputation: 765

Empty DataGrid WPF

I have List based on class (id, name, code, price) and im trying to add that values to datagrid. Problem is that, datagrid is still empty, i mean look like that: enter image description here

XAML

<DataGrid AutoGenerateColumns="False" Height="275" HorizontalAlignment="Left" Margin="337,51,0,0" Name="dataGridProducts" VerticalAlignment="Top" Width="403" Foreground="#FF803E3E">
    <DataGrid.Columns>
        <DataGridTextColumn Header="ID" Width="30" />
        <DataGridTextColumn Header="Nazwa" Width="200" />
        <DataGridTextColumn Header="Kod" Width="120" />
        <DataGridTextColumn Header="Cena" Width="100" />
    </DataGrid.Columns>
</DataGrid>

Code Behind:

private void categoryListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    SqlConnection SqlConn = new SqlConnect().ConnectToSql();
    using (SqlConn)
    {
        SqlConn.Open();
        SqlCommand fillCategories = new SqlCommand("...", SqlConn);
        SqlDataReader rdr1;
        rdr1 = fillCategories.ExecuteReader();
        while (rdr1.Read())
        {
            Products p = new Products(rdr1.GetInt32(rdr1.GetOrdinal("ID")), rdr1.GetString(rdr1.GetOrdinal("ProductName")), rdr1.GetString(rdr1.GetOrdinal("Barcode")), rdr1.GetString(rdr1.GetOrdinal("Price")));
            completeProductList.Add(p);
        }
    }
    dataGridProducts.ItemsSource = completeProductList;
}

Is there any solution how to fix it?

Upvotes: 0

Views: 1952

Answers (1)

Rafael A. M. S.
Rafael A. M. S.

Reputation: 637

You must bind the column to a value in the class of the datagrid items Source

Example: If your datagrid.ItemsSource is a table with 3 columns:

    - ID
    - Name
    - Address

You must bind each column of the datagrid to a column of the table:

    ...
<DataGridTextColumn Header="ID" Binding="{Binding Path=ID}" Width="Auto" />
<DataGridTextColumn Header="Name" Binding="{Binding Path=Name}" Width="Auto" />
<DataGridTextColumn Header="Address" Binding="{Binding Path=Address}" Width="Auto" />
...

Then you'll see the bound values of the table.

Upvotes: 4

Related Questions