문제

여러 행과 열로 구성된 DatagridView가 있습니다. 각 행을 반복하고 특정 열의 내용을 확인하고 싶습니다. 해당 열에 "아니오"라는 단어가 포함되어 있으면 전체 행의 예측기를 빨간색으로 변경하고 싶습니다. 여기에 지금까지 일부 코드에 대한 시도가 있지만 모든 셀을 반복 해야하는지 궁금해지기 시작하는 것은 확실히 작동하지 않습니다.

암호:

foreach (DataGridViewRow dgvr in dataGridView1.Rows)
        {
            if (dgvr.Cells["FollowedUp"].Value.ToString() == ("No"))
            {
                dgvr.DefaultCellStyle.ForeColor = Color.Red;
            }
        }
도움이 되었습니까?

해결책 3

public void ColourChange()
    {
        DataGridViewCellStyle RedCellStyle = null;
        RedCellStyle = new DataGridViewCellStyle();
        RedCellStyle.ForeColor = Color.Red;
        DataGridViewCellStyle GreenCellStyle = null;
        GreenCellStyle = new DataGridViewCellStyle();
        GreenCellStyle.ForeColor = Color.Green;


        foreach (DataGridViewRow dgvr in dataGridView1.Rows)
        {
            if (dgvr.Cells["FollowedUp"].Value.ToString().Contains("No"))
            {
                dgvr.DefaultCellStyle = RedCellStyle;
            }
            if (dgvr.Cells["FollowedUp"].Value.ToString().Contains("Yes"))
            {
                dgvr.DefaultCellStyle = GreenCellStyle;
            }
        }
    }

다른 팁

연결 onrowdatabound 이벤트는 일을합니다

ASPX (그리드) :

    <asp:.... OnRowDataBound="RowDataBound"..../>

뒤에 코드 :

    protected void RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowIndex == -1)
        {
            return;
        }

        if(e.Row.Cells[YOUR_COLUMN_INDEX].Text=="NO"){
             e.Row.BackColor=Color.Red;   
        }
    }

Winforms의 경우 :

hook the **DataBindingComplete** event and do stuff in it:

     private void dataGridView1_DataBindingComplete(object sender, 
                       DataGridViewBindingCompleteEventArgs e)
    {
        if (e.ListChangedType != ListChangedType.ItemDeleted)
        {
            DataGridViewCellStyle red = dataGridView1.DefaultCellStyle.Clone();
            red.BackColor=Color.Red;

            foreach (DataGridViewRow r in dataGridView1.Rows)
            {
                if (r.Cells["FollowedUp"].Value.ToString()
                       .ToUpper().Contains("NO"))
                {
                    r.DefaultCellStyle = red;
                }
            }
        }
    }

DataGridView에서 CellFormatting 이벤트를 처리합니다.

dataGridView1.CellFormatting += new DataGridViewCellFormattingEventHandler(dataGridView1_CellFormatting);

이벤트 핸들러는 다음과 같이 보일 수 있습니다.

private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{       
    if(dataGridView1.Columns[e.ColumnIndex].Name == "FollowedUp" && e.Value != null && e.Value.ToString() == "No")
        dataGridView1.Rows[e.RowIndex].DefaultCellStyle.ForeColor = Color.Red;  
}

이런 식으로 당신은 행을 통해 '반복'하지 않습니다. 단순히 그리드에서 눈에 띄게 될 때 페인트/그리기 색상을 변경하십시오 (따라서 서식이 필요합니다).

셀 값의 일부로 공백이나 다른 캐릭터가있을 수 있습니까? 그렇다면 직선 평등보다는 포함 방법을 사용해보십시오.

if (dgvr.Cells["FollowedUp"].Value.ToString().Contains("No"))

이것은 Winforms를위한 솔루션입니다.

private void HighlightRows()
{
    DataGridViewCellStyle GreenStyle = null;

    if (this.dgridv.DataSource != null)
    {
        RedCellStyle = new DataGridViewCellStyle();
        RedCellStyle.BackColor = Color.Red;

        for (Int32 i = 0; i < this.dgridv.Rows.Count; i++)
        {
            if (((DataTable)this.dgridv.DataSource).Rows[i]["col_name"].ToString().ToUpper() == "NO")
            {
                this.dgridv.Rows[i].DefaultCellStyle = RedCellStyle;
                continue;
            }
        }
    }
}

이 코드는 나에게 잘 작동합니다.


foreach (DataGridViewRow row in dataGridView1.Rows)
{
    if ((string)row.Cells["property_name"].Value == UNKNOWN_PROPERTY_NAME)
    {
        row.DefaultCellStyle.BackColor = Color.LightSalmon;
        row.DefaultCellStyle.SelectionBackColor = Color.Salmon;
    }
}

Tostring을 부르는 대신 문자열로 캐스팅하는 것 외에는 실제로 차이가 없으므로 케이스 민감도 버그가 될 수 있습니다. 사용해보십시오 :

dgvr.Cells["FollowedUp"].Value.ToString().ToUpper() == "NO"
private void Grd_Cust_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    colorCode == 4 ? Color.Yellow : Color.Brown;
    if (e.RowIndex < 0 || Grd_Cust.Rows[e.RowIndex].Cells["FollowedUp"].Value == DBNull.Value)
        return;
    string colorCode = Grd_Cust.Rows[e.RowIndex].Cells["FollowedUp"].Value.ToString();
    e.CellStyle.BackColor = colorCode == "NO" ? Color.Red : Grd_Cust.DefaultCellStyle.BackColor;
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top