Programing

datagridview에서 행 색상을 변경하는 방법은 무엇입니까?

lottogame 2020. 6. 26. 08:09
반응형

datagridview에서 행 색상을 변경하는 방법은 무엇입니까?


내 datagridview에서 특정 행의 색상을 변경하고 싶습니다. columncell 7의 값이 columncell 10의 값보다 작 으면 행이 빨간색으로 변경되어야합니다.이를 수행하는 방법에 대한 제안 사항이 있습니까?


datagridview에서 행을 반복 한 다음 각 행에서 열 7과 10의 값을 비교해야합니다.

이 시도:

foreach (DataGridViewRow row in vendorsDataGridView.Rows) 
     if (Convert.ToInt32(row.Cells[7].Value) < Convert.ToInt32(row.Cells[10].Value)) 
     {
         row.DefaultCellStyle.BackColor = Color.Red; 
     }

방금이 문제를 조사하고 있었으므로 (이 질문은 거의 3 년 전에 게시되었지만 누군가에게 도움이 될 것입니다 ...) 더 나은 옵션은 RowPrePaint이벤트 내부에 코드를 배치하여 사용자가하지 않도록하는 것 같습니다 모든 행을 통과해야하며 페인트 된 행만 통과해야하므로 대량의 데이터에서 훨씬 더 나은 성능을 발휘합니다.

이벤트에 첨부

this.dataGridView1.RowPrePaint 
    += new System.Windows.Forms.DataGridViewRowPrePaintEventHandler(
        this.dataGridView1_RowPrePaint);

이벤트 코드

private void dataGridView1_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
{
    if (Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells[7].Text) < Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells[10].Text)) 
    {
        dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Beige;
    }
}

당신은 CellFormatting이벤트를 찾고 있습니다.
다음 은 예입니다.


텍스트 색상도 변경하는 데 문제가있었습니다. 색상이 변경된 것을 본 적이 없습니다.

내가 코드를 추가 할 때까지 이벤트에 텍스트 색상을 변경하기 DataBindingsComplete위해 DataGridView. 그 후 그것은 효과가있었습니다.

나는 이것이 같은 문제에 직면하는 사람들을 도울 수 있기를 바랍니다.


셀의 값이 정수라고 가정하면 다음과 같은 것이 있습니다.

foreach (DataGridViewRow dgvr in myDGV.Rows)
{
  if (dgvr.Cells[7].Value < dgvr.Cells[10].Value)
  {
    dgvr.DefaultCellStyle.ForeColor = Color.Red;
  }
}

테스트되지 않았으므로 오류에 대해 사과드립니다.

특정 행을 알고 있으면 반복을 건너 뛸 수 있습니다.

if (myDGV.Rows[theRowIndex].Cells[7].Value < myDGV.Rows[theRowIndex].Cells[10].Value)
{
  dgvr.DefaultCellStyle.ForeColor = Color.Red;
}

어떤 사람들은 Paint, CellPainting또는 CellFormatting이벤트 를 사용하기를 원 하지만 이러한 이벤트에서 스타일을 변경하면 재귀 호출이 발생합니다. 사용 DataBindingComplete하면 한 번만 실행됩니다. 에 대한 논거 CellFormatting는 보이는 셀에서만 호출되므로 보이지 않는 셀을 포맷 할 필요는 없지만 여러 번 포맷하는 것입니다.


당신은 변경 할 수 있습니다 Backcolor적용 후 condition.and이 함수 호출을 사용하여 행 단위 DatasourceDatagridView.

여기 그 기능이 있습니다. 간단히 복사해서 넣습니다Databind

private void ChangeRowColor()
{
    for (int i = 0; i < gvItem.Rows.Count; i++)
    {
        if (BindList[i].MainID == 0 && !BindList[i].SchemeID.HasValue)
            gvItem.Rows[i].DefaultCellStyle.BackColor = ColorTranslator.FromHtml("#C9CADD");
        else if (BindList[i].MainID > 0 && !BindList[i].SchemeID.HasValue)
            gvItem.Rows[i].DefaultCellStyle.BackColor = ColorTranslator.FromHtml("#DDC9C9");
        else if (BindList[i].MainID > 0)
            gvItem.Rows[i].DefaultCellStyle.BackColor = ColorTranslator.FromHtml("#D5E8D7");
        else
            gvItem.Rows[i].DefaultCellStyle.BackColor = Color.White;
    }
}

private void dtGrdVwRFIDTags_DataSourceChanged(object sender, EventArgs e)
{
    dtGrdVwRFIDTags.Refresh();
    this.dtGrdVwRFIDTags.Columns[1].Visible = false;

    foreach (DataGridViewRow row in this.dtGrdVwRFIDTags.Rows)
    {
        if (row.Cells["TagStatus"].Value != null 
            && row.Cells["TagStatus"].Value.ToString() == "Lost" 
            || row.Cells["TagStatus"].Value != null 
            && row.Cells["TagStatus"].Value.ToString() == "Damaged" 
            || row.Cells["TagStatus"].Value != null 
            && row.Cells["TagStatus"].Value.ToString() == "Discarded")
        {
            row.DefaultCellStyle.BackColor = Color.LightGray;
            row.DefaultCellStyle.Font = new Font("Tahoma", 8, FontStyle.Bold);
        }
        else
        {
            row.DefaultCellStyle.BackColor = Color.Ivory;
        }
    }  

    //for (int i= 0 ; i<dtGrdVwRFIDTags.Rows.Count - 1; i++)
    //{
    //    if (dtGrdVwRFIDTags.Rows[i].Cells[3].Value.ToString() == "Damaged")
    //    {
    //        dtGrdVwRFIDTags.Rows[i].Cells["TagStatus"].Style.BackColor = Color.Red;                   
    //    }
    //}
}

이것은 bindingDataSource를 사용하여 색상을 dataGridView로 변경하는 솔루션입니다.

private void dataGridViewECO_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{            

    if (e.ListChangedType != ListChangedType.ItemDeleted)
    {

        DataGridViewCellStyle green = this.dataGridViewECO.DefaultCellStyle.Clone();
        green.BackColor = Color.Green;

        DataGridViewCellStyle gray = this.dataGridViewECO.DefaultCellStyle.Clone();
        gray.BackColor = Color.LightGray;



        foreach (DataGridViewRow r in this.dataGridViewECO.Rows)
        {

            if (r.Cells[8].Value != null)
            {

                String stato = r.Cells[8].Value.ToString();


                if (!" Open ".Equals(stato))
                {
                    r.DefaultCellStyle = gray;
                }
                else
                {
                    r.DefaultCellStyle = green;
                }
            }

        }

    }
}

If you bind to a (collection) of concrete objects, you can get the that concrete object via the DataBoundItem property of the row. (To avoid check for magic strings in the cell and using "real" properties of the object)

Skeleton example below:

DTO/POCO

public class Employee
{
    public int EmployeeKey {get;set;}

    public string LastName {get;set;}

    public string FirstName {get;set;}

    public bool IsActive {get;set;}
}       

Binding to the datagridview

    private void BindData(ICollection<Employee> emps)
    {
        System.ComponentModel.BindingList<Employee> bindList = new System.ComponentModel.BindingList<Employee>(emps.OrderBy(emp => emp.LastName).ThenBy(emp => emp.FirstName).ToList());
        this.dgvMyDataGridView.DataSource = bindList;
    }       

then the event handler and getting the concrete object (instead of a DataGridRow and/or cells)

        private void dgvMyDataGridView_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
        {
            Employee concreteSelectedRowItem = this.dgvMyDataGridView.Rows[e.RowIndex].DataBoundItem as Employee;
            if (null != concreteSelectedRowItem && !concreteSelectedRowItem.IsActive)
            {
                dgvMyDataGridView.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.LightGray;
            }
        }

I typically Like to use the GridView.RowDataBound Event event for this.

protected void OrdersGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        e.Row.ForeColor = System.Drawing.Color.Red;
    }
}

Works on Visual Studio 2010. (I tried it and it works!) It will paint your entire row.

  1. Create a button for the datagridview.
  2. Create a CellClick event and put the next line of code inside of it.

if (dataGridView3.Columns[e.ColumnIndex].Index.Equals(0)    
{
    dataGridView3.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Beige;
}

You have not mentioned how value is changed. I have used similar functionality when user is entering value. i.e. entering and leaving edit mode.

Using CellEndEdit event of datagridview.

private void dgMapTable_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
    double newInteger;

    if (double.TryParse(dgMapTable[e.ColumnIndex,e.RowIndex].Value.ToString(), out newInteger)
    {
        if (newInteger < 0 || newInteger > 50)
        {
            dgMapTable[e.ColumnIndex, e.RowIndex].Style.BackColor = Color.Red; 

            dgMapTable[e.ColumnIndex, e.RowIndex].ErrorText 
                = "Keep value in Range:" + "0 to " + "50";
        }
    }                               
}

You may add logic for clearing error notification in a similar way.

if in your case, if data is loaded programmatically, then CellLeave event can be used with same code.


With this code, you only change rows backcolor where columname value is null other rows color still the default one.

       foreach (DataGridViewRow row in dataGridView1.Rows)
                {
                    if (row.Cells["columnname"].Value != null)
                    {
                        dataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.MistyRose;
                    }
                 }

Just a note about setting DefaultCellStyle.BackColor...you can't set it to any transparent value except Color.Empty. That's the default value. That falsely implies (to me, anyway) that transparent colors are OK. They're not. Every row I set to a transparent color just draws the color of selected-rows.

I spent entirely too much time beating my head against the wall over this issue.


int counter = gridEstimateSales.Rows.Count;

        for (int i = 0; i < counter; i++)
        {
            if (i == counter-1)
            {
                //this is where your LAST LINE code goes
                //row.DefaultCellStyle.BackColor = Color.Yellow;
                gridEstimateSales.Rows[i].DefaultCellStyle.BackColor = Color.Red;
            }
            else
            {
                //this is your normal code NOT LAST LINE
                //row.DefaultCellStyle.BackColor = Color.Red;
                gridEstimateSales.Rows[i].DefaultCellStyle.BackColor = Color.White;
            }
        }

I landed here looking for a solution for the case where I dont use data binding. Nothing worked for me but I got it in the end with:

dataGridView.Columns.Clear(); 
dataGridView.Rows.Clear();
dataGridView.Refresh();

참고URL : https://stackoverflow.com/questions/2189376/how-to-change-row-color-in-datagridview

반응형