Statesプロパティが設定されているときに行に色を付けるDataGridViewがあります。
Statesは、セミコロンで区切られた数値リストを表す文字列です。
私が受け取っ"0;1;2"
た場合、最初の3つの行は、それぞれ紫、緑、赤で色付けされます。
問題は、列ヘッダーをクリックしてデータグリッドを並べ替えるときに発生します。色は同じ方法で適用されます。
例えば :
Names|Labels
Name1|Label1
Name2|Label2
Name3|Label3
私は"0;1;2"
それを意味し"Purple;Green;Red"
ます:
Names|Labels
Name1|Label1 => Purple
Name2|Label2 => Green
Name3|Label3 => Red
並べ替え(降順):
Names|Labels
Name3|Label3 => Red
Name2|Label2 => Green
Name1|Label1 => Purple
私は"3;4;5"
それを意味し"Yellow;Orange;Pink"
ます:
Names|Labels
Name3|Label3 => Yellow
Name2|Label2 => Orange
Name1|Label1 => Pink
しかし、これは私が待っていたものではありません、私はそれが欲しかったです:
Names|Labels
Name3|Label3 => Pink
Name2|Label2 => Orange
Name1|Label1 => Yellow
これが私のコードです:
protected String m_States;
public virtual String States
{
get { return m_States; }
set {
m_States = value;
if (m_bRunning)
{
UpdateColors();
}
}
}
private void UpdateColors()
{
String[] sStates = new String[] { };
if (m_States != null)
{
sStates = m_States.Split(m_sSeparators);
int nState = 0;
int nRowNumber = 0;
foreach (System.Windows.Forms.DataGridViewRow row in Rows)
{
nState = int.Parse(sStates[nRowNumber]);
if (nState < 0 || nState > m_Couleurs_Fond_Etats.Length)
{
nState = m_Couleurs_Fond_Etats.Length - 1;
}
row.DefaultCellStyle.BackColor = m_Couleurs_Fond_Etats[nState];
row.DefaultCellStyle.ForeColor = m_Couleurs_Texte_Etats[nState];
row.DefaultCellStyle.SelectionBackColor = m_Couleurs_Sel_Fond_Etats[nState];
row.DefaultCellStyle.SelectionForeColor = m_Couleurs_Sel_Texte_Etats[nState];
nState = 0;
++nRowNumber;
}
}
}
DataGridViewに追加された順序で行にアクセスする方法はありませんか?
PS:私は最初にnRowNumberの代わりにrow.Indexを使用したので、問題はそれが原因であると信じていましたが、明らかに、Rowsコレクションが再編成されるか、foreachがrowIndexesに従って解析します。
=====LarsTechの回答のおかげで私が使用したソリューションは次のとおりです=====
行を追加した後、次のようにタグを付けました。
foreach(System.Windows.Forms.DataGridViewRow row in Rows)
{
row.Tag = row.Index;
}
次に、このタグを行番号として使用できます。
private void UpdateColors()
{
String[] sStates = new String[] { };
if (m_States != null)
{
sStates = m_States.Split(m_sSeparators);
int nState = 0;
int nRowNumber = 0;
foreach (System.Windows.Forms.DataGridViewRow row in Rows)
{
nRowNumber = Convert.ToInt32(row.Tag);
if (nRowNumber >= 0 && nRowNumber < sEtats.Length)
{
nState = int.Parse(sStates[nRowNumber]);
if (nState < 0 || nState > m_Couleurs_Fond_Etats.Length)
{
nState = m_Couleurs_Fond_Etats.Length - 1;
}
row.DefaultCellStyle.BackColor = m_Couleurs_Fond_Etats[nState];
row.DefaultCellStyle.ForeColor = m_Couleurs_Texte_Etats[nState];
row.DefaultCellStyle.SelectionBackColor = m_Couleurs_Sel_Fond_Etats[nState];
row.DefaultCellStyle.SelectionForeColor = m_Couleurs_Sel_Texte_Etats[nState];
nState = 0;
}
}
}
}