简体   繁体   中英

datatable as an itemsource for datagrid in wpf

How can I set a datagrid control values from a datatable ?

I use this source

    public static readonly DependencyProperty ObjDataTableDefaultViewProperty = DependencyProperty.Register("ObjDataTableDefaultView", typeof(System.Data.DataView), typeof(Window1), new FrameworkPropertyMetadata());

    public System.Data.DataView ObjDataTableDefaultView
    {
        get { return (System.Data.DataView)GetValue(ObjDataTableDefaultViewProperty); }
        set { SetValue(ObjDataTableDefaultViewProperty, value); }
    }
    private void CreateObjDataTable()
    {
        try
        {
            ObjDataTableDefaultView = table.DefaultView;
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

But it has got an error message and the program stops,

A first chance exception of type 'System.Windows.Markup.XamlParseException' occurred in PresentationFramework.dll

Additional information: Cannot create instance of 'Window1' defined in assembly 'ReadSky, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. Exception has been thrown by the target of an invocation. Error in markup file 'Window1.xaml' Line 1 Position 9.

 My XAML

<Window x:Class="ReadSky.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="296" Width="738" xmlns:my="http://schemas.microsoft.com/wpf/2008/toolkit">
    <Grid>
        <my:DataGrid AutoGenerateColumns="False" Margin="36,30,39,90" Name="gridCtrl" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" IsReadOnly="True" RowBackground="Gray" AlternatingRowBackground="White" ItemsSource="{Binding ObjDataTableDefaultView, ElementName=uc, Mode=OneWay}"/>
    </Grid>
</Window>

You could try this:

 <DataGrid Name="grid" AutoGenerateColumns="True" ItemsSource="{Binding}" />     

 public DataTable TableData {
        get {
            DataTable dt = new DataTable();
            dt.Columns.Add("col1");
            dt.Columns.Add("col2");
            dt.Rows.Add(new string[] {"val1", "val2"});
            return dt;
        }
    }

 grid.DataContext = TableData;

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