我有一个使用这些代码填充的datagrid:
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;
}
我想将数据从数据库插入到数据库表。我尝试通过以下方式通过数据编进行迭代:
foreach (DataRowView dr in dgItems.ItemsSource)//ERROR HERE
{ }
但它给了我一个错误:" system.invalidcastException:无法将'type'items'的对象施加到type'system.data.datarowview'
我该怎么办?
它是因为您的项目源包含"项目"的集合,并且您已将其声明为" dataRowView" foreach循环。
这样使用:
foreach (items dr in DataGrid1.ItemsSource) //ERROR HERE
{
}
或
foreach (var dr in DataGrid1.ItemsSource) //ERROR HERE
{
}