遍历每个项目WPF DataGrid

时间:2016-02-01 12:27:52

标签: c# wpf datagrid

我有2个网格,一个是国家,另一个是程序。现在我想将Country(s)或Program(s)的组合添加到Third DataGrid中选择的形式。
数据绑定到dgProgramme [GridView]如下

using (DataSet dataset = DBHandler.GetProgramme())
{
    dgProgramme.ItemsSource = dataset.Tables[0].DefaultView;
}

数据绑定到国家[DataGrid]如下

using (DataSet ds = DBHandler.GetCountries())
{
    dgCountries.ItemsSource = ds.Tables[0].DefaultView;
}

现在我想将选定值添加到第三个DataGrid中,称为gRolesForUser 当前代码将选定值添加到新的[gRolesForUser]网格中。然而,它没有检查重复,这就是为什么我计划检查套管组合是否存在而不是添加到DataGrid [gRolesForUser]

var itemsSource = dgRolesForUser.ItemsSource as IEnumerable;
if (itemsSource != null)
{
    foreach (var drv  in itemsSource)
    {
       // Here I want to check that SelectedItems not Exists into using something like follows 
       if(PersonId != [dgRolesForUser].CountryId && CountryName !=[dgRolesForUser].CountryName)
       //then add to list 
        _user.Roles.Add(
        new PersonRole()
        {
            PersonId = _user.PersonId,
            Amount = string.IsNullOrWhiteSpace(txtDefaultAmount.Text) ? null : (Decimal?)Convert.ToDecimal(txtDefaultAmount.Text),
            CountryId = Convert.ToInt32(((DataRowView)dgCountries.SelectedItems[i])["CountryId"]),
            RoleId = Convert.ToInt32(cmbRole.SelectedValue.ToString()),
            CountryName = (((DataRowView)dgCountries.SelectedItems[i])["Name"]).ToString(),
            ProgrammeName = (((DataRowView)dgProgramme.SelectedItems[j])["Name"]).ToString(),
            RoleName = cmbRole.Text.ToString()
        }
    );
    }
}

1 个答案:

答案 0 :(得分:0)

使用LINQ

var itemsSource = dgRolesForUser.ItemsSource as IEnumerable<PersonRole>;
if(itemsSource.All(item => item.CountryId != PersonId  && item.CountryName != CountryName)
{
    // Combination does not exist, add new role here
}

(猜测您的ItemsSourceIEnumerable<PersonRole>