如何在c#中正确地遍历数据网格

本文关键字:遍历 数据 数据网 网格 正确地 | 更新日期: 2023-09-27 18:07:23

我希望能够设置DataGrid的行背景。

我的第一个想法是这样做:

//MapDisplay is a DataGrid
SolidColorBrush myBrush = new SolidColorBrush(Colors.Red);
mapDisplay.RowBackground = myBrush;

现在,这是有效的,但它将为DataGrid中的每一行设置背景。我的下一个想法是这样做:

SolidColorBrush myBrush = new SolidColorBrush(Colors.Red);
foreach (DataGridRow x in mapDisplay.Items)
{
    x.Background = myBrush;
}

然而,这不会导致任何行的背景改变,所以我假设我做了一些根本性的错误。我如何正确地遍历DataGrid的行来设置背景?

如何在c#中正确地遍历数据网格

你的问题被标记为WPF,这是winforms的答案…

DataGridView行样式与行模板(DataGridViewCellStyle类)。

下面是一组拼接在一起的代码片段,用于向网格添加行。theGrid是我们要向其添加行的控件。事件是从数据库返回的POCO。

                var rowCellStyle = new DataGridViewCellStyle(theMessagesGrid.DefaultCellStyle)
                {
                    BackColor = string.IsNullOrEmpty(conditions) 
                           ? theGrid.DefaultCellStyle.BackColor 
                           : theColor,
                    SelectionForeColor = Color.WhiteSmoke,
                    SelectionBackColor = theGrid.DefaultCellStyle.SelectionBackColor,
                };
            var theRow = new DataGridViewRow 
                { 
                   Height = theGrid.RowTemplate.Height, 
                   DefaultCellStyle = rowCellStyle, 
                   Tag = Event.GroupName 
                };
            theRow.CreateCells(theGrid);
            var cellData = new object[theRow.Cells.Count];
            // fill out cell data
            cellData[0] = ...;
            cellData[1] = ...
            theRow.SetValues(cellData);
            // add row to grid
            try
            {
                theGrid.Rows.Add(theRow);
                if (currentMsg == Event.Pkey) theGrid.Rows[theGrid.Rows.Count - 1].Selected = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, @"Error Building Grid", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                throw;
            }

WPF应该有一些样式应用于行。添加存储行模板的表单属性,然后根据条件更新rowCellStyle。

要更改特定行的背景,需要根据其DataContextindex的某些值获取该行。

然后将Trigger/DataTrigger应用于RowStyle

通过编程方式,您可以使用以下命令获得基于ItemDataGridRow:
DataGridRow row = (DataGridRow) mapDisplay.ItemContainerGenerator.ContainerFromItem(item);

mapDisplay.Items将给你一个有界项的列表,可以是Map objects,或者一般的Employee对象。

ContainerFromIndex() method

现在,修改你的代码,

   foreach (object o in mapDisplay.Items)
   {
        Map m = o as Map;
        if (m == null) break;
        if (m.AreaCode == 1234)
        {
            DataGridRow row = (DataGridRow)mapDisplay.ItemContainerGenerator.ContainerFromItem(m);
            row.Background = Brushes.Yellow;
        }
    }