Ребята подскажите, пожалуйста, как изменить цвет строки целиком в зависимости от значения одной из ячеек в этой строке.
Например
Есть таблица
OrgID OrdName Phone
1 OOO "1" (null)
0 Подразделение1 2222222
0 Подразделение2 3333333
1 OOO "2" (null)
0 Подразделение1 5222222
0 Подразделение2 5333333
Цвет строки где OrgID =1 должен отличаться от остальных
... << RSDN@Home 1.1.3 stable >>
Здравствуйте, igor_andru, Вы писали:
_>Ребята подскажите, пожалуйста, как изменить цвет строки целиком в зависимости от значения одной из ячеек в этой строке.
См. также:
RSDN DataGrid FAQ — Раскраска ячеек в зависимости от значенияАвтор(ы): SiAVoL, Beker
Дата: 31.10.2004
Рассматриваются вопросы, наиболее часто возникающие при использовании класса System.Windows.Forms.DataGrid из .NET Framework Class Library.
George Shepherd’s Windows Forms FAQ (
http://www.syncfusion.com/FAQ/WinForms/) в моем очень вольном и неполном переводе...
5.14 Как раскрасить отдельные ячейки в зависимости от значения в них или какой-либо внешней функции?
Предлагаем три различных метода решения проблемы:
Первый из них перекрывает Paint в порожденном columnstyle и устанавливает там цвет фона.
Второй использует делегат для установки цвета в перекрытом Paint.
Третий метод добавляет событие в порожденном column style — для того чтобы позволить вам устанавливать цвет в обработчике сообщения.
Метод 1
Это можно сделать, породившись от DataGridTextBoxColumn и перекрыв метод Paint, чтобы установить backColor и foreColor в зависимости от условия. Приведенный ниже пример закрашивает все ячейки, текст в которых начинается на символ, больший чем «F». Вы можете загрузить проект (
C#,
VB) использующий этот класс.
C#
public class DataGridColoredTextBoxColumn : DataGridTextBoxColumn
{
protected override void Paint(System.Drawing.Graphics g,
System.Drawing.Rectangle bounds, System.Windows.Forms.CurrencyManager
source, int rowNum, System.Drawing.Brush backBrush, System.Drawing.Brush
foreBrush, bool alignToRight)
{
// the idea is to conditionally set the foreBrush and/or backbrush
// depending upon some crireria on the cell value
// Here, we color anything that begins with a letter higher than 'F'
try{
object o = this.GetColumnValueAtRow(source, rowNum);
if( o!= null)
{
char c = ((string)o)[0];
if( c > 'F')
{
// could be as simple as
// backBrush = new SolidBrush(Color.Pink);
// or something fancier...
backBrush = new LinearGradientBrush(bounds,
Color.FromArgb(255, 200, 200),
Color.FromArgb(128, 20, 20),
LinearGradientMode.BackwardDiagonal);
foreBrush = new SolidBrush(Color.White);
}
}
}
catch(Exception ex){ /* empty catch */ }
finally{
// make sure the base class gets called to do the drawing with
// the possibly changed brushes
base.Paint(g, bounds, source, rowNum, backBrush, foreBrush, alignToRight);
}
}
}
VB.NET
Public Class DataGridColoredTextBoxColumn
Inherits DataGridTextBoxColumn
Public Sub New()
End Sub
Protected Overloads Overrides Sub Paint(ByVal g As Graphics, _
ByVal bounds As Rectangle, ByVal source As CurrencyManager, _
ByVal rowNum As Integer, ByVal backBrush As Brush, _
ByVal foreBrush As Brush, ByVal alignToRight As Boolean)
' the idea is to conditionally set the foreBrush and/or backbrush
' depending upon some crireria on the cell value
' Here, we color anything that begins with a letter higher than 'F'
Try
Dim o As Object
o = Me.GetColumnValueAtRow(source, rowNum)
If (Not (o) Is Nothing) Then
Dim c As Char
c = CType(o, String).Substring(0, 1)
If (c > "F") Then
' could be as simple as
' backBrush = new SolidBrush(Color.Pink);
' or something fancier...
backBrush = New LinearGradientBrush(bounds, _
Color.FromArgb(255, 200, 200), _
Color.FromArgb(128, 20, 20), _
LinearGradientMode.BackwardDiagonal)
foreBrush = New SolidBrush(Color.White)
End If
End If
Catch ex As Exception
' empty catch
Finally
' make sure the base class gets called to do the drawing with
' the possibly changed brushes
MyBase.Paint(g, bounds, source, rowNum, backBrush, foreBrush, alignToRight)
End Try
End Sub
End Class
Метод 2
To use some method to provide the cell color, you can use a similar technique as discussed above. But instead of setting the color based on cell value, call a delegate method instead. This delegate can be passed in using the constructor for the custom column style. You can
download a sample that shows how this can be done.
Метод 3
If you want a more flexible solution, you could expose an event as part of your derived columnstyle that fires in the Paint override. This would allow the handler of the event to set the color value depending upon the row and column parameters that are passed as part of the event args. You can download a sample (
C#,
VB) that implements this technique. The sample actually handles allowing a cell to be editable on a cell by cell basis through an event. This sample colors the back ground of the disabled cell gray. You could modify the eventargs to include a backcolor, and use this event to color cells based on row and column values removing the event call in the Edit override.
Здравствуйте,
Большое спасибо всем кто не остался ровнодушным
Может я чего не понял но проблемму так и не решил
Как раскрасить конкретную ячайку в зависимости от ЕЁ значения я нашел а вот как
изменить цвет ячейки в зависимости от ЗНАЧЕНИЯ ДРУГОЙ ЯЧЕЙКИ
Делов том что из метода Paint() DataGridTextBox(а) Обратиться к соседней ячейке у меня не получается и также как и к самому dataGrid(у)
... << RSDN@Home 1.1.3 stable >>
Согласен
... << RSDN@Home 1.1.3 stable >>
?, 29.05.05 06:01
>Раскараска dataGrid
Рассмотри вариант:
1. Введи в таблицу уникальный ключ (лучше суррогатный).
2. Свяжи таблицу (лучше её DataView) с сеткой (DataGrid).
3. Переопредели метод Paint сетки. Одним из входных параметров метода есть "int rowNum" содержащий номер текущей строки сетки. Используя примерно такую функцию, получишь номер строки
DataView, ассоциированной со строкой сетки
//-- Поиск строки в DataView по GUID
//=================================
internal int FindRow(Guid guid, DataView dv)
{
//if(guid==app.ssnGuid) return -1; //-- Если строка не найдена
//-- Перебором находим строку по guid
for(int i=0;i<dv.Count;i++) {
if (guid == (Guid)dv
[0])return i;
}
return -1; //-- Если строка не найдена
}
Дальше, дело техники. Я использую в качестве суррогатного ключа Guid, вы можете просто пронумеровать строки таблицы и что-то другое. Решать вам.
[i]данное сообщение получено с www.gotdotnet.ru
ссылка на оригинальное сообщение
Узнать в Paint значение в ячейке текущей строки DataGrid с номером столбца nnn можно так:
source.List.Item(rowNum).Row.ItemArray(nnn)
Здесь source и rowNum — параметры Paint.
данное сообщение получено с www.gotdotnet.ru
ссылка на оригинальное сообщение