迭代数据网格会产生错误:"无法转换类型"

时间:2018-02-28 03:18:59

标签: c# wpf

我有一个数据网格,我使用这些代码填充:

public class items
{
    public string prfNo { get; set; }
    public string mrsNo { get; set; }
    public string itemName { get; set; }
    public string qty { get; set; }
    public string uom { get; set; }
    public string model { get; set; }
    public string brand { get; set; }
    public string remarks { get; set; }
    public string status { get; set; }
    public string purp { get; set; }
    public string approvedBy { get; set; }
    public string dateApproved { get; set; }
    public string preparedBy { get; set; }
    public string datePrepared { get; set; }
}

private void fillDatagrid()
    {
        if (chkNewItem.IsChecked == true)
        {
            purpose = "NEW ITEM";
        }
        else if (chkStock.IsChecked == true)
        {
            purpose = "STOCK";
        }
        else if (chkOthers.IsChecked == true)
        {
            purpose = txtOthers.Text;
        }

        ObservableCollection<items> itemData = new ObservableCollection<items>()
        {
            new items()
            {
                prfNo  = txtPRFNo.Text,
                mrsNo = txtMRSNo.Text,
                itemName = txtItem.Text,
                qty = txtQty.Text,
                uom = txtUOM.Text,
                model = txtModel.Text,
                brand = txtBrand.Text,
                remarks = txtRemarks.Text,
                status = txtStatus.Text,
                purp = purpose,
                approvedBy = txtApprovedBy.Text,
                dateApproved = txtApprovedDate.Text,
                preparedBy = txtPreparedBy.Text,
                datePrepared = txtPreparedDate.Text
            }
        };

        dgItems.ItemsSource = itemData;
    }

我希望将数据从datagrid插入数据库表。 我尝试使用:

迭代数据网格
foreach (DataRowView dr in dgItems.ItemsSource)//ERROR HERE
{ } 

但是它给了我一个错误:&#34; System.InvalidCastException:无法转换类型&#39; items&#39;输入&#39; System.Data.DataRowView&#39;

我该怎么办?

1 个答案:

答案 0 :(得分:0)

因为您的ItemsSource包含“items”的集合,并且您已在foreach循环中将其声明为“DataRowView”。

像这样使用:

foreach (items dr in DataGrid1.ItemsSource) //ERROR HERE
{
}

OR

foreach (var dr in DataGrid1.ItemsSource) //ERROR HERE
{            
}