在WPF中读取数据网格的值

时间:2017-04-05 11:58:47

标签: c# wpf datagrid

我需要读取WPF应用程序中数据网格中列的所有值。

for (int i = 0; i < dgridList.Items.Count; i++)
            {
                DataGridRow row = (DataGridRow)dgridList.ItemContainerGenerator.ContainerFromIndex(i);

                TextBlock t_name = dgridList.Columns[0].GetCellContent(row) as TextBlock;
                TextBlock t_type = dgridList.Columns[1].GetCellContent(row) as TextBlock;
                Tuple<string, string> mod = new Tuple<string, string>(t_name.Text, t_type.Text);
                Alist.Add(mod);
            }

这是datagrid的XMAL声明

<DataGrid x:Name ="dgridList" Margin="0,0,0,0" Grid.Row="1" IsReadOnly="True" AutoGenerateColumns="False">

如果数据网格仅包含3,4个项目,则此迭代正常工作(如果我们在数据网格迭代中添加更多项目并不起作用。)。如果我们增加项目,婴儿车栏也可见。 (因为数据网格大小设置为小)

An unhandled exception of type 'System.ArgumentNullException' occurred in PresentationFramework.dll

Additional information: Value cannot be null.

如果我尝试读取数据网格中的值(超过4个项目),我收到此错误。

我该如何解决这个问题。

2 个答案:

答案 0 :(得分:2)

如果您已将ItemsSource的{​​{1}}属性设置为DataGrid,则可以遍历所有IEnumerable<YourClass>个对象并获取其属性值:

YourClass

答案 1 :(得分:1)

<强> XAML

<DataGrid  ColumnWidth="*" 
       IsReadOnly="True"
       AutoGenerateColumns="False"
       SelectionMode="Single" 
       HorizontalScrollBarVisibility="Auto"
       VerticalScrollBarVisibility="Auto"
       ScrollViewer.CanContentScroll="True"
       ItemsSource="{Binding MyData}"
       SelectedItem="{Binding Item}"
 >
<DataGrid.Columns>
    <DataGridTextColumn Header="Nº." Binding="{Binding NumberProperty}" MinWidth="100" With="Auto"/>
    <DataGridTextColumn Header="Name" Binding="{Binding NameProperty}" Width="*"/>
</DataGrid.Columns>

ViewModel (首先需要实施INotifyPropertyChanged

private ObservableCollection<MyData> _myData;
private MyData _selectdItem;

public ObservableCollection<MyData> DataCollection 
{
    get { return _myData; }
    set { _myData = value; OnPropertyChanged("DataCollection"); }
}
//Your current selected item in the datagrid
public MyData Item
{
    get { return _selectdItem; }
    set
    {
        _selectdItem = value;
        OnPropertyChanged("Item");
    }
}
private void ReadAllItems()
{
    foreach (var item in DataCollection)
    {
        var mod = new Tuple<string, string>(item.Number, item.Name);
        Alist.Add(mod);
    }
}
private void LoadDataCollection()
{
    using (var db = new YourContext())
    {
        //Your DataGrid will fill here
        DataCollection = new ObservableCollection<MyData> ( db.YourEntity.List() )
    }
}