简体   繁体   English

如何将数据动态添加到 WPF DataGrid

[英]How to dynamically add data to WPF DataGrid

I'm new in WPF and I'd like to visualize data from SQL query to WPF DataGrid.我是 WPF 的新手,我想将 SQL 查询中的数据可视化到 WPF DataGrid。 I have problem with a how correctly bind a data:我对如何正确绑定数据有疑问:

SqlCommand cmd = new SqlCommand(sql_dotaz, conn);
InfoText.Text += ("Příkaz vytvořen a připojen" + "\n");

try
{
    conn.Open();
    InfoText.Text += ("Připojení otevřeno" + "\n");

    SqlDataReader reader = cmd.ExecuteReader();

    int row_count = reader.FieldCount;  
    ArrayList propoj = new ArrayList();

    for (int i = 0; i < row_count; i++)
    {
        propoj.Add(reader.GetName(i));
        tabView.Columns.Add(new DataGridTextColumn 
            { 
                Header = reader.GetName(i), 
                Binding = new Binding(reader.GetName(i)) 
            });

        //Here is the problem!!!
        tabView.Items.Add(new {propoj[i] = "Hello"});
    }

Problem is when a try to add a new item, it's throws an error.问题是当尝试添加新项目时,它会引发错误。 I cannot explicitly set the header name like this (Invitation = "Hello").我无法像这样显式设置标题名称(Invitation =“Hello”)。

I also tried

tabView.Columns.Add(new DataGridTextColumn 
    { 
        Header = reader.GetName(i), 
        Binding = new Binding(reader.GetName(i)) 
    });

string record = reader.GetName(i));
tabView.Items.Add(new {record = "Hello"});

But there is still a problem with the header name - The DataGrid is empty.但是标题名称仍然存在问题 - DataGrid 为空。

Please let me know if you have any ideas.如果您有任何想法,请告诉我。 Thanks a lot!非常感谢!

First of all, I don't think anonymous types will work in a binding.首先,我认为匿名类型不会在绑定中工作。 You'll somehow have to create a wrapper object for that:您必须以某种方式为此创建一个包装器对象:

// easiest case
public class DatabaseObject
{
    public List<string> Items = new List<string>();
}

With that, you can easily generate your columns:有了它,您可以轻松生成列:

// this should be renamed in something like columns or fieldCount...
int row_count = reader.FieldCount;  

for (int i = 0; i < row_count; i++)
{
    tabView.Columns.Add(new DataGridTextColumn 
        { 
            Header = reader.GetName(i), 
            Binding = new Binding("Items[i]") 
        });
}

And fill your DataGrid:并填写您的 DataGrid:

if(reader.HasRows)
{
    do
    {
        DatabaseObject obj = new DatabaseObject();
        for (int i = 0; i < row_count; i++)
        {
            obj.Items.Add(reader.GetString(i));
        }

        tabView.Items.Add(obj);
    }
    while(reader.NextResult());
}

You need to manage this with DataBinding , as you specified WPF like technology in tags.您需要使用DataBinding来管理它,因为您在标签中指定了类似 WPF 的技术。

Example links :示例链接:

Link1 链接1

Link 2 链接 2

Link 3 链接 3

if wanna go the easy way:如果想走简单的路:

  1. fill a datatable with your data.用您的数据填充数据表。
  2. simply bind the itemssource from the datagrid to your datatable.只需数据网格中的项目源绑定到您的数据表。 (Read about DataBinding and MVVM) (阅读有关数据绑定和 MVVM 的信息)

    <DataGrid ItemsSource="{Binding MyFilledDataTableProperty}" />

  3. set the right datacontext.设置正确的数据上下文。

In the I find the solution.在我找到解决方案。 Maybe it´s not best but it´s work.也许这不是最好的,但它的工作。 I create DataSet and SQL Adapter我创建了数据集和 SQL 适配器

adapter.Fill(dSet);
this.DataContext = dSet.Tables[0].DefaultView;

and in XAML:在 XAML 中:

<DataGrid Height="Auto" Width="Auto" Name="tabView3" ItemsSource="{Binding}" />

And now it´s work fine :-)现在它工作正常:-)

This is what worked for me:这对我有用:

IN THE XAML FILE:在 XAML 文件中:

    <DataGrid Name="YourDataGrid"  CanUserAddRows="true" AutoGenerateColumns="False" RowDetailsVisibilityMode="VisibleWhenSelected" Width="auto" SelectionUnit="FullRow" RowEditEnding="YourDataGrid_RowEditEnding" AddingNewItem="YourDataGrid_AddingNewItem">
            <DataGrid.Columns>
                <DataGridTextColumn x:Name="VideoID_column" Binding="{Binding IDVideo, NotifyOnTargetUpdated=True, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Header="Video ID" Width="SizeToHeader"/>
                <DataGridTextColumn x:Name="VideoTitle_column" Binding="{Binding Titlu,NotifyOnTargetUpdated=True, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Header="Title" Width="auto"/>
            </DataGrid.Columns>
        </DataGrid>

IN THE .CS File在 .CS 文件中

        private void YourDataGrid_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e)
    {
        if (e.EditAction == DataGridEditAction.Commit && isInsertMode == true)
        {
            var vid = e.Row.DataContext as video;

            var context = new YourEntities();
            var Video = new video //video is the class
            {

                IDVideo = vid.IDVideo,
                Titlu = vid.Titlu
            };
            context.videos.Add(Video);
            context.SaveChanges();
        }
    }

    private void YourDataGrid_AddingNewItem(object sender, AddingNewItemEventArgs e)
    {
        isInsertMode = true;
    }

Hope that helps!希望有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM