如何以编程方式将数据添加到WPF数据网格

时间:2012-08-14 10:24:40

标签: c# wpf datagrid

如何在WPF中以编程方式将数据项添加到DataGrid哪些没有绑定? DataGrid有4列。

3 个答案:

答案 0 :(得分:14)

目前还不是很清楚,你喜欢做什么。我想,你已经定义了一个你想放置DataGrid的地方。为了便于说明,我创建了一个新的WPF项目并使用chridram提供的代码,该代码发布了第一个答案。

在下面的MainWindow.xaml中,我将Grid MainGrid命名为在后面的代码中访问它:

<Window x:Class="WpfExperiments.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid Name="MainGrid"/>
</Window>

DataItem类不是WPF类,而是由Yourself创建的自定义类:

public class DataItem
{
    public string Column1 { get; set; }
    public string Column2 { get; set; }
    public string Column3 { get; set; }
    public string Column4 { get; set; }
}

要让DataGrid以编程方式显示存储在DataItem对象中的数据,您可以执行以下操作:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        // Your programmatically created DataGrid is attached to MainGrid here
        var dg = new DataGrid();
        this.MainGrid.Children.Add(dg);

        // create four columns here with same names as the DataItem's properties
        for (int i = 1; i <= 4; ++i)
        {
            var column = new DataGridTextColumn();
            column.Header = "Column" + i;
            column.Binding = new Binding("Column" + i);
            dg.Columns.Add(column);
        }

        // create and add two lines of fake data to be displayed, here
        dg.Items.Add(new DataItem { Column1 = "a.1", Column2 = "a.2", Column3 = "a.3", Column4 = "a.4" });
        dg.Items.Add(new DataItem { Column1 = "b.1", Column2 = "b.2", Column3 = "b.3", Column4 = "b.4" });
    }
}

我希望这会有所帮助。

问候 约尔格

答案 1 :(得分:2)

这是一个用于从数据库中检索数据的函数     , '%Y-%m-%d' )

SELECT a.id, a.clientId, a.enrollDate, a.cancelDate FROM gap_borrower a WHERE STR_TO_DATE( a.`loanEndDate` ,  '%Y-%m-%d' ) >= STR_TO_DATE(  '2015-12-31',  '%Y-%m-%d' ) AND FIND_IN_SET( a.status,  'A,C' ) AND (CASE WHEN a.cancelDate IS NOT NULL THEN (STR_TO_DATE( a.`enrollDate` ,  '%Y-%m-%d' ) <> STR_TO_DATE(  a.cancelDAte,  '%Y-%m-%d' )) END  ) 

答案 2 :(得分:0)

enter image description here

.xaml:

<DataGrid x:Name="dataGrid" Margin="10">
    <DataGrid.Columns>
        <DataGridCheckBoxColumn Binding="{Binding Path=Column1}"/>
        <DataGridTextColumn Binding="{Binding Path=Column2}"/>
    </DataGrid.Columns>
</DataGrid>

.cs:

public class DataItem
{
    public bool Column1 { get; set; }
    public string Column2 { get; set; }
}

/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        DataItem item = new DataItem();
        item.Column1 = true;
        item.Column2 = "test";
        dataGrid.Items.Add(item);
    }
}