How to get the Style.BackColor of a datagridview c

2019-08-11 01:49发布

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

3条回答
Deceive 欺骗
2楼-- · 2019-08-11 02:25

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;
查看更多
放荡不羁爱自由
3楼-- · 2019-08-11 02:32

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

enter image description here

if i supress the comment slashes

I get this

enter image description here

查看更多
迷人小祖宗
4楼-- · 2019-08-11 02:49

In the click event

if dgvNotes.Rows(clickedCell.RowIndex).Cells(1).Style.BackColor = Color.Red then
查看更多
登录 后发表回答