简体   繁体   English

根据 excel 表中的值获取单元格范围/位置,并在 c# 中为单元格数据网格视图着色

[英]Get cell range/location based on value at excel sheet and colour the cell datagridview in c#

I'm displaying the imported excel sheet in data grid view.我在数据网格视图中显示导入的 excel 工作表。 based on the row name, I'm replacing the specific cell strings.基于行名称,我正在替换特定的单元格字符串。 Now I want to colour the specific cells based on their values.现在我想根据它们的值给特定的单元格上色。

 private void Replace_strings()
    {
        TextInfo textInfo = new CultureInfo("en-US", false).TextInfo;
        DataTable dt = dataGridView1.DataSource as DataTable;

        foreach (DataRow r in dt.Select("[SET 1] = 'First Name'"))
            for (int y = 1; y < r.ItemArray.Length; y++)
            {
                String str = r[y].ToString();
                r[y] = str.Replace('0', 'o');
                r[y] = textInfo.ToUpper(r[y].ToString());

                if (r[y].ToString().Contains("%"))
                {

                   //If a cell contains "%"I want to mark that cell in red colour
                  //CellStyle.BackColor = Color.Red;
                    //CellStyle.ForeColor = Color.White;


                }

            }
    }

How do I efficiently correct this我如何有效地纠正这个

EXPECTED预期的

Click to view the expected output image点击查看预期output图

There are numerous ways to do this.有很多方法可以做到这一点。 I would loop through the “Grid” instead of the data source.我会循环遍历“网格”而不是数据源。 The DataTable contains the data, however the “grid” displays it. DataTable包含数据,但是“网格”显示它。 Because of this, it is the “grid” where you want to change the color not the data.table.因此,您要更改颜色的是“网格”,而不是 data.table。

However, looping through the grid may not be necessary if you wire up a couple of the grids events.但是,如果您连接了几个网格事件,则可能没有必要在网格中循环。

The grid has numerous “CellFormatting/Painting” events you could use, however, you want to be careful which one you use.网格有许多您可以使用的“CellFormatting/Painting”事件,但是,您要小心使用哪一个。 Most of these events get fired often, even if a cells value has not changed.大多数这些事件经常被触发,即使单元格值没有改变。 In other words, if the grid gets repainted because the grid is scrolled, it is a wasted effort to re-format the cell since it has not changed.换句话说,如果网格因为滚动而被重新绘制,那么重新格式化单元格是一种浪费,因为它没有改变。

Given this, I suggest you wire up two (2) of the grid's events… the CellEndEdit event... this event will fire when a cells value changes and the user attempts to leave the cell.鉴于此,我建议您连接两 (2) 个网格事件…… CellEndEdit事件……当单元格值更改并且用户尝试离开单元格时,将触发此事件。 When this event fires, the code should look for the “%” and format accordingly.当此事件触发时,代码应查找“%”并相应地设置格式。

The CellEndEdit event will work when changes are made “after” the grid has been loaded with data.当网格加载数据“之后”进行更改时, CellEndEdit事件将起作用。 Unfortunately, the CellEndEdit event will NOT fire when the data is “initially” loaded into the grid.不幸的是,当数据“最初”加载到网格中时, CellEndEdit事件不会触发。 To help, the second event, RowsAdded is used, this event will fire when “new” rows are added to the grid.为了提供帮助,使用了第二个事件RowsAdded ,当“新”行添加到网格时将触发此事件。 It is in this event where we can loop through each cell in the row and set the color accordingly.正是在这个事件中,我们可以遍历行中的每个单元格并相应地设置颜色。

Example…例子…

Wire up the grids two events…连接网格两个事件......

public Form1() {
  InitializeComponent();
  dataGridView1.CellEndEdit += new DataGridViewCellEventHandler(dataGridView1_CellEndEdit);
  dataGridView1.RowsAdded += new DataGridViewRowsAddedEventHandler(dataGridView1_RowsAdded);
}

Since we need to format the cells “independently” is makes sense to create a method such that given a DataGridViewCell the method will check the cells value and format it accordingly.由于我们需要“独立”格式化单元格,因此创建一个方法是有意义的,这样给定一个DataGridViewCell ,该方法将检查单元格值并相应地格式化它。 This method will come in handy in both events.这种方法在这两种情况下都会派上用场。 The method may look like…该方法可能看起来像……

private void FormatACell(DataGridViewCell cell) {
  if (cell.Value != null && cell.Value.ToString().Contains("%")) {
    cell.Style.BackColor = Color.Red;
  }
  else {
    cell.Style.BackColor = Color.White;
  }
}

Next the two events…接下来的两个事件......

private void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e) {
  DataGridViewRow row = dataGridView1.Rows[e.RowIndex];
  foreach (DataGridViewCell cell in row.Cells) {
    FormatACell(cell);
  }
}

private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e) {
  DataGridViewCell cell = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];
  FormatACell(cell);
}

Lastly, to complete the example…最后,为了完成这个例子……

DataTable dt;

private void Form1_Load(object sender, EventArgs e) {
  dt = GetDataFromDB();
  dataGridView1.DataSource = dt;
}

private DataTable GetDataFromDB() {
  DataTable dt = new DataTable();
  dt.Columns.Add("Col1", typeof(string));
  dt.Columns.Add("Col2", typeof(string));
  dt.Columns.Add("Col3", typeof(string));
  dt.Rows.Add("Data1", "Dat%a2", "Data3");
  dt.Rows.Add("Data2%", "Data3", "Data1");
  dt.Rows.Add("Data3", "Data2", "Da%ta1");
  return dt;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM