迭代绑定列表以查找属性

时间:2016-02-24 01:34:25

标签: c# user-interface devexpress

我有一个名为bList的BindingList,它正在GUI中使用。

public BindingList<SomeList> bList = new BindingList<SomeList>();

我想要做的是通过检查bList中的属性来更改事件的RowStyle。让我们在bList中说我有6个具有多个属性的对象。我所拥有的bList中的一个属性称为isValid,它是bool,如果将其设置为false,则将该行变为红色,否则该行将保持默认颜色。 / p>

如果>= 0,我可以让所有行变为红色。如何迭代bList以查找isValid中每个对象的属性blist

private void gridView_RowStyle(object sender, RowStyleIEventArgs e)
{
    bool isValid = class.bList[0].isValid;

    if (e.RowHandle >= 0)
    {
        if (isValid == false)
        {
            e.Appearance.BackColor = Color.Red;
        }
    }
}

3 个答案:

答案 0 :(得分:1)

您应该使用反射来获取对象的属性值。这是一个适用于通用BindingList的示例函数。

使用:

    for (int i = 0; i < myList.Count; i++)
    {
        object val = null;
        TryGetPropertyValue<SomeType>(myList, i, "isValid", out val);
        bool isValid = Convert.ToBoolean(val);
        // Process logic for isValid value
    }

方法:

static private bool TryGetPropertyValue<T>(BindingList<T> bindingList, int classIndex, string propertyName, out object val)
    where T : class
    {
        try
        {
            Type type = typeof(T);
            PropertyInfo propertyInfo = type.GetProperty(propertyName);

            val = propertyInfo.GetValue(bindingList[classIndex], null);

            return val != null; // return true if val is not null and false if it is
        }
        catch (Exception ex)
        {
            // do something with the exception
            val = null;

            return false;
        }
    }

答案 1 :(得分:1)

要根据属性值更改行的颜色,应将该属性添加为隐藏列,然后使用该单元格的值设置样式。

请参阅以下内容: How to change a row style based on a column value

对于你的问题:

private void gridView_RowCellStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowCellStyleEventArgs e)
{
   string valid = gridView.GetRowCellValue(e.RowHandle, "isValid").ToString().ToLower();
   if(valid == "true") 
      e.Appearance.BackColor = Color.Red;
}

添加隐藏列: Hide Column in GridView but still grab the values

答案 2 :(得分:0)

我现在能够迭代BindingList bList,因为我还有其他一些继承问题试图找出迭代器的类型。

foreach (SomeType item in bList)
{
     if (e.RowHandle >= 0)
     {
          if (instance.isValid == false)
          {
              e.Appearance.BackColor = Color.Red;
          }
          else
          {
              e.Appearance.BackColor = Color.White;
          }
     }
}

即使我找到属性isValid的哪个对象正在返回false,所有行仍然会变为红色。