There is a DataGridView in it come values ​​from the database, where for a certain period the cell is highlighted in red.

But over time, the base has grown greatly, and a color filter was required. On one of the forums I found

 private void checkBox1_CheckedChanged(object sender, EventArgs e) { foreach (DataGridViewRow r in dataGridview1.Rows) { if(r.DefaultCellStyle.BackColor == Color.Red) { } } } 

But it loads the process a lot and it doesn’t work, and I don’t know where to put the result.

UPD

  if(datagridview.rows[e.rowindex].Cells["Срок_до"].value !=null &&((DateTime)datagridview.rows[e.rowindex].Cells["Срок_до"].valu‌​e).CompareTo(datetim‌​e <0) { datagridview.rows[e.Rowindex].defaultcellstyle = color.red } for (var index = 0; index<datagridview.Columns.Count; ++index) { var formattedvalue = datagridview.Rows[e.RowIndex].Cell[index].FormattedValue; if(formattedvalue==null) continue; var str = formattedvalue.ToString().ToLower(); if(str!="удален") { if(str=="неограничен") datagridview.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Yellow; } else datagridview.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Gray; } } 

Data from the database

 Adapter = new MySqlDataAdapter("SELECT * FROM dist", new MySqlConnection(Connect.ToString())); Adapter.Fill(dt); datagrid.DataSource = dt; 

UPD is now filtered like this:

 var dataview = new DataView(dt) { RowFilter = $"Срок_до < '{datetime}' AND Комментарии = '' AND Статус_отработки = ''" } 

But there is a snag because there are 3 colors and you need to make it so that only 1 color is red.

UPD

Added a picture So now, white there confidential information

Please help

  • 3
    WinForms? Add a tag. It is necessary not to check the color of the cell, but the value in the bound collection or, in general, sorting in the database. - Alexander Petrov
  • one
    Но со временем база сильно разрослась, и потребовалась сортировка по цвету... What is the relationship between the size of the database and sorting by color? - sp7
  • @ sp7 by the time when a certain date comes it colors in red. If (datagrid.rows [e.rowindex] .Cells ["Deadline to]]. Value! = Null && ((DateTime) datagrid.rows [e.rowindex] .Cells [" Deadline to "]. Value) .CompareTo (datetime < 0) datagrid.rows [e.Rowindex] .defaultcellstyle = color.red - Paul
  • Do not write the code in the comments, move it to the question by pressing the edit button. And specify how the data gets into the grid: manually entered or using a binding? - Alexander Petrov
  • @AlexanderPetrov Made changes as data comes from the database - Pavel

2 answers 2

Correct filter:

 var dataview = new DataView(dt) { RowFilter = $"Срок_до < '{datetime}' AND Isnull(Комментарии, '') = '' AND Isnull(Статус_отработки, '') = ''" } 

    Highlighting a color value is the work of the view.

    Hang the CellFormatting event handler on the DataGridView and write the following code in it:

     private void DataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) { if (e.ColumnIndex == 2) // индекс нужной колонки { if (e.Value != null && (DateTime)e.Value < dateTime) e.CellStyle.BackColor = Color.Red; } } 

    As a result, the desired cells are highlighted in color.

    Now sorting. This is already the work of the data layer, it should not be done in the grid itself.

    In general, it is automatically executed when the user clicks on the header (header) of the grid column. But if you want to do a sorting by pressing your own button, then this is done simply due to data binding. Since the data is placed in the DataTable , its capabilities and use:

     private void SortButton_Click(object sender, EventArgs e) { dt.DefaultView.Sort = "Time"; // имя колонки, по которой сортируем } 

    Just take a DataView and use its Sort property. Please note that at the same time, an arrow appears on the grid column - the sort icon.

    By default, sorting is done in ascending order. If you need to do in descending order, we write:

     dt.DefaultView.Sort = "Time desc"; 

    If you wish, you can sort by several columns at the same time, it is enough to specify them separated by commas:

     "Time, Id" 
    • Thanks for the answer, but it doesn’t suit me very much. I need all the cells except the red ones to go. DataView, RowFilter - Pavel
    • @Pavel - what's the problem? So write in RowFilter condition for comparing with the date. - Alexander Petrov
    • Something I can not catch up with the condition. - Pavel
    • it works like RowFilter = $ "Term_Up <<datetime}" but the problem is that there is one more color gray it shows it - Paul
    • @Pavel show a screenshot of the current result - Ev_Hyper