我有一个数据的数据网格视图,数据行是彩色的(仅文本着色)如下:红色,橙色和黑色 例如:
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
switch (e.Value.ToString())
{
case "SDP":
e.Value = "Schedule Departure";
this.dataGridView1.Rows[e.RowIndex].DefaultCellStyle.ForeColor = Color.Red;
break;
case "CKN":
e.Value = "Check-In";
this.dataGridView1.Rows[e.RowIndex].DefaultCellStyle.ForeColor = Color.Orange;
break;
case "P2G":
e.Value = "Proceed to Gate";
this.dataGridView1.Rows[e.RowIndex].DefaultCellStyle.ForeColor = Color.Black;
break;
}
我还创建了包含少量单选按钮的Groupbox来更改支持
private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
ListSortDirection direction;
direction = ListSortDirection.Ascending;
dataGridView1.Sort(arrTimeDataGridViewTextBoxColumn,direction);
}
但问题是:如何根据文本的颜色更改排序,例如:RED,ORANGE然后是Black?
答案 0 :(得分:0)
在datagridview
中创建一个列,您可以在其中保留一些ForeColor
。
例如:
列将命名为dataGridView_ForeColorNum
,值将显示为下一个:
RED = 1
ORANGE = 2
BLACK = 3
然后在处理程序dataGridView1_CellFormatting
中设置此值同时更改行的ForeColor
cswitch (e.Value.ToString())
{
case "SDP":
e.Value = "Schedule Departure";
this.dataGridView1.Rows[e.RowIndex].DefaultCellStyle.ForeColor = Color.Red;
this.dataGridView1.Rows[e.RowIndex].Cells[dataGridView_ForeColorNum.Name].Value = 1;
break;
case "SKN":
e.Value = "Check-In";
this.dataGridView1.Rows[e.RowIndex].DefaultCellStyle.ForeColor = Color.Orange;
this.dataGridView1.Rows[e.RowIndex].Cells[dataGridView_ForeColorNum.Name].Value = 2;
break;
case "P2G":
e.Value = "Proceed to gate";
this.dataGridView1.Rows[e.RowIndex].DefaultCellStyle.ForeColor = Color.Black;
this.dataGridView1.Rows[e.RowIndex].Cells[dataGridView_ForeColorNum.Name].Value = 3; break;
}
排序将正常,但用于对具有ForeColor的数字的新列进行排序:
private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
ListSortDirection direction;
direction = ListSortDirection.Ascending;
dataGridView1.Sort(dataGridView_ForeColorNum,direction);
}
对于数据绑定DataGridView以前的解决方案将无法工作,因为预定义列的属性IsDataBound
= False。 MSDN:datagridview.Sort
在这种情况下,我想到的第一个解决方案是:
在您的SQL查询中添加一个列,您可以使用ForeColor
语句设置CASE WHEN
号码:
CASE yourValueColumn
WHEN 'SDP' THEN 1
WHEN 'SKN' THEN 2
WHEN 'P2G' THEN 3
ELSE 0 END AS ForeColor
在datagridview的预定义列dataGridView_ForeColorNum
中,设置属性DataProperty = "ForeColor"
和datagridview_CellFormatting
处理程序将如下所示:
{
if(this.datagridview1.Columns[e.ColumnIndex].Name != this.dataGridView_ForeColorNum.Name)
return;
//if column is ForeColumn then set a ForeColor independent on the column value
switch ((int)e.Value)
{
case 1: //SDP
e.Value = "Schedule Departure";
this.dataGridView1.Rows[e.RowIndex].DefaultCellStyle.ForeColor = Color.Red;
break;
case 2: //SKN
e.Value = "Check-In";
this.dataGridView1.Rows[e.RowIndex].DefaultCellStyle.ForeColor = Color.Orange;
break;
case 3: //P2G
e.Value = "Proceed to gate";
this.dataGridView1.Rows[e.RowIndex].DefaultCellStyle.ForeColor = Color.Black;
break;
}
}