How to get the Style.BackColor of a datagridview cell

假如想象 提交于 2019-12-24 07:39:13

问题


Using VS2010 VB.NET, I have a datagridview (dgv) where I set the background color of cells according to a certain value. This particular cell does not store any information and therefore I can not use the data in that cell to determine the background color.

My current attempts are a complete failure and MSDN is only particular to "setting" and not "getting" the background color of a cell.

Code I've tried"

if dgvNotes.Rows(clickedCell.RowIndex).Cells(1).Style.BackColor.ToString = "Red" then

if dgvNotes.Rows(clickedCell.RowIndex).Cells(1).Style.BackColor = Color.Red then

I am not able to find much information on the topic as most of the posts on various coding sites focusses on "setting" the background color.

Is there any way that I can determine cell background color after the dgv was populated ? Thanks


回答1:


write in cell click event

// using vb.net
System.Drawing.Color c = dgvNotes.Rows(e.RowIndex).Cells(1).Style.BackColor;

//using c#
System.Drawing.Color c = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.BackColor;



回答2:


In the click event

if dgvNotes.Rows(clickedCell.RowIndex).Cells(1).Style.BackColor = Color.Red then



回答3:


This is not working for me

I have this code for setting the cells color and other properties

    public static void SetDgvHeader(DataGridView dgv,DataGridView clonedgv,string tarih,string[] dgv_Headers)
    {
        dgv.Rows.Clear();
        dgv.ColumnCount = dgv_Headers.Length;
        dgv.RowHeadersVisible = false;
        int dayNbr = int.Parse(datenbr.txt);
        dgv.Rows.Add(dayNbr);
        for (int i = 0; i < dgv_Headers.Length; ++i)
        {
            if (i == 1 || i == 3 || i == 5)
            {
                dgv.Columns[i].Width = 20;
                dgv.Columns[i].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            }
            else
            {
                dgv.Columns[i].Width = 78;
                clonedgv.Columns[i].Width = 78;
            }
            dgv.Columns[i].HeaderText = dgv_Headers[i];
            dgv.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;
            dgv.Columns[i].ReadOnly = true;
        }
        for (int i = 0; i < dayNbr; ++i)
        {
            dgv.Rows[i].Height = 20;
            for (int a = 0; a < dgv_Headers.Length; ++a)
            {
                dgv.Rows[i].Cells[a].Style.BackColor = Color.White;
                dgv.Rows[i].Cells[a].Value = "";
           }
        }
        dgv.Height = (dayNbr* dgv.Rows[0].Height) + 25;
        dgv.AllowUserToAddRows = false;

When I comment the line where I add the white color I get this

if i supress the comment slashes

I get this



来源:https://stackoverflow.com/questions/23844778/how-to-get-the-style-backcolor-of-a-datagridview-cell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!