简体   繁体   中英

Nothing shows up in datagrid wpf

I am using datagrid view. Data gets added in the table and from the watch window, I can see that there is 1 row included in table but nothing gets displayed in datagrid.

Here is the code:

 DataTable PopulateDataGrids(DataGrid grid, List<RetrievedEmailData> data)
 {
            DataTable table = new DataTable();
            table.Columns.Add("Sr No");
            table.Columns.Add("Company Name");
            table.Columns.Add("Email");

            int count = 0;

            DataRow row;

            foreach (RetrievedEmailData item in data)
            {
                count++;
                row = table.NewRow();
                row["Sr No"] = count.ToString();
                row["Company Name"] = item.Name;
                row["Email"] = item.Email;
                table.Rows.Add(row);
            }
            return table;
        }

This is the method call:

dataGridBoatCompanyList.DataContext = PopulateDataGrids(dataGridBoatCompanyList, boat);

XAML markup:

<DataGrid AutoGenerateColumns="True" Height="322" HorizontalAlignment="Left" Margin="6,6,0,0" Name="dataGridBoatCompanyList" VerticalAlignment="Top" Width="500" />

Try adding ItemsSource="{Binding}" to your grid

<DataGrid DataContext="{Binding}" AutoGenerateColumns="True" Height="322" HorizontalAlignment="Left" Margin="6,6,0,0" Name="dataGridBoatCompanyList" VerticalAlignment="Top" Width="500" />

also, you in your method, PopulateDataGrids() the first parameter is not being used. If all you are trying to do is populate the grid then you can skip that method and just use

dataGridBoadCompanyList.ItemsSource = new ObservableCollection<RetrievedEmailData>(boat); 

EDIT:

If I try this

void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
            dataGridBoatCompanyList.ItemsSource =
                new ObservableCollection<RetrievedEmailData>(new[]
                                                                 {
                                                                     new RetrievedEmailData
                                                                         {Email = "dfsd", Name = "fadsfds"}
                                                                 });
        }

and

<DataGrid ItemsSource="{Binding}" AutoGenerateColumns="True" Height="322" HorizontalAlignment="Left" Margin="6,6,0,0" Name="dataGridBoatCompanyList" VerticalAlignment="Top" Width="500" />

I get a populated list like this

在此处输入图片说明

很难看到DataGrid的XAML定义,但是也许您是想这样做

dataGridBoatCompanyList.ItemsSource = PopulateDataGrids(dataGridBoatCompanyList, boat);

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