颜色整行而不是单个单元格

时间:2012-10-16 06:26:17

标签: c# datagrid compact-framework

我一直在尝试更改Compact Framework DataGrid中一行的背景颜色,但由于.NET CF上的DataGrid与Windows Forms对应版本相比有限,因此收效甚微。我实现目标的唯一成功是,我现在能够根据其值更改单个单元格的背景颜色。我无法操纵我从谷歌搜索获得的代码,因为我在C#中不是那么好。但是,这是我的代码:

namespace GridColor
{
    public delegate void CheckCellEventHandler(object sender, DataGridEnableEventArgs e);

    public class DataGridEnableEventArgs : EventArgs
    {
        private int _column;
        private int _row;
        private bool _meetsCriteria;

        public DataGridEnableEventArgs(int row, int col, bool val)
        {
            _row = row;
            _column = col;
            _meetsCriteria = val;
        }

        public int Column
        {
            get { return _column; }
            set { _column = value; }
        }

        public int Row
        {
            get { return _row; }
            set { _row = value; }
        }

        public bool MeetsCriteria
        {
            get { return _meetsCriteria; }
            set { _meetsCriteria = value; }
        }

    }

    public partial class ColumnStyle : DataGridTextBoxColumn
    {
        //public event CheckCellEventHandler CheckCellEquals;
        public event CheckCellEventHandler CheckCellContains;

        private int _col;

        public ColumnStyle(int column)
        {
            _col = column;
        }

        protected override void Paint(Graphics g, Rectangle Bounds, CurrencyManager Source, int RowNum, Brush BackBrush, Brush ForeBrush, bool AlignToRight)
        {
            bool enabled = true;

            if (CheckCellContains != null)
            {
                DataGridEnableEventArgs e = new DataGridEnableEventArgs(RowNum, _col, enabled);
                CheckCellContains(this, e);
                if (e.MeetsCriteria)
                    //g.DrawRectangle(new Pen(Color.Red, 2), Bounds.Y + 1, Bounds.Width - 2, Bounds.Height - 2);
                    BackBrush = new SolidBrush(Color.PaleGreen);
            }

            base.Paint(g, Bounds, Source, RowNum, BackBrush, ForeBrush, AlignToRight);

        }
    }

}

现在我的表格,我有这个:

namespace GridColor
    {
        public partial class Form1 : Form
        {
            DataSet ds;
            SqlDataAdapter da;
            private List<string> compareValues = new List<string>();

            public Form1()
            {
                InitializeComponent();
                try
                {
                    addGridStyle(ref dataGrid1);
                    compareValues.Add("OK");
                    compareValues.Add("Filling");
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error: " + ex.ToString());
                }
            }

            private void addGridStyle(ref DataGrid dg)
            {
                DataGridTableStyle dtStyle = new DataGridTableStyle();
                dtStyle.MappingName = "Test";

                string connString = "Data Source=192.168.2.16,1433;Initial Catalog=TestDB;User ID=sa;Password=ABC12abc;";
                SqlConnection conn = new SqlConnection(connString);
                conn.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = conn;
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = "SELECT * FROM Test";
                ds = new DataSet();
                da = new SqlDataAdapter(cmd);
                da.Fill(ds, "Test");

                for (int i = 0; i < ds.Tables["Test"].Columns.Count; i++)
                {
                    ColumnStyle myStyle = new ColumnStyle(i);
                    myStyle.MappingName = ds.Tables["Test"].Columns[i].ToString();
                    if (i == 1)
                    {
                        if (ds.Tables["Test"].Columns[i].DataType == System.Type.GetType("System.String"))
                            myStyle.CheckCellContains += new CheckCellEventHandler(myStyle_CheckCellContains);
                    }
                    dtStyle.GridColumnStyles.Add(myStyle);
                }

                dg.TableStyles.Add(dtStyle);
            }

            public void myStyle_CheckCellContains(object sender, DataGridEnableEventArgs e)
            {
                try
                {
                    if (compareValues.Contains((string)dataGrid1[e.Row, e.Column]))
                        e.MeetsCriteria = true;
                    else
                        e.MeetsCriteria = false;
                }
                catch (Exception ex)
                {
                    e.MeetsCriteria = false;
                }
            }

            private void Form1_Load(object sender, EventArgs e)
            {
                dataGrid1.DataSource = ds.Tables["Test"];
            }
        }
    }

我应该在代码的哪个部分进行更改,以便如果某个单元符合条件,则整行将被着色而不仅仅是它自己的单元格?

2 个答案:

答案 0 :(得分:1)

好吧,我回去找了几年前的代码,我在桌面上做了​​这个,在更高级的DataGridView出来之前等等。

首先,Microsoft Customizing the Windows Forms DataGrid提供了本教程,其中介绍了如何突出显示整行。

我查看了我的代码,我必须为每个列添加一个自定义列样式,向我处理的主窗体发出一个事件,然后确定该记录的正确颜色。然后,我设置args.Color属性,DataGridColumn将绘制正确的颜色。 所以,是的,你必须让每一列成为你的自定义格式化类,然后你的应用程序逻辑可以处理事件,获取记录数据并确定颜色

**更新:这是一个简单的例子**

public partial class Form1 : Form
{
    FormattableTextBoxColumn firstNameColumn = new FormattableTextBoxColumn();
    FormattableTextBoxColumn lastNameColumn = new FormattableTextBoxColumn();

    public Form1()
    {
        InitializeComponent();

        // add first name col
        firstNameColumn.MappingName = "FirstName";
        dataGridTableStyle1.GridColumnStyles.Add(firstNameColumn);
        firstNameColumn.SetCellFormat += new FormatCellEventHandler(ColumnSetCellFormat);

        // add last name col
        lastNameColumn.MappingName = "LastName";
        lastNameColumn.SetCellFormat += new FormatCellEventHandler(ColumnSetCellFormat);
        dataGridTableStyle1.GridColumnStyles.Add(lastNameColumn);

        // This just sets up a dummy data source, since I don't have a database in this example
        List<PersonTest> peopleList = new List<PersonTest>();
        peopleList.Add(new PersonTest
        {
            FirstName = "Alan",
            LastName = "QQQQQ",
            HighlightPerson = true
        });
        peopleList.Add(new PersonTest
        {
            FirstName = "John",
            LastName = "Smith",
            HighlightPerson = false
        });
        BindingSource peopleDataSource = new BindingSource();
        peopleDataSource.DataSource = peopleList;
        dataGridTableStyle1.MappingName = peopleDataSource.GetListName(null);
        dataGrid1.DataSource = peopleDataSource;
    }

    // I'll cache this brush in the form, just make sure to dispose it (see designer.cs disposing)
    SolidBrush highlightBrush = new SolidBrush(Color.Yellow);

    // here is the event you can handle to determine the color of your row!
    private void ColumnSetCellFormat(object sender, DataGridFormatCellEventArgs e)
    {
        if ((e.Source.List[e.Row] as PersonTest).HighlightPerson)
            e.BackBrush = highlightBrush;
    }

    // example test class
    public class PersonTest
    {
        public String FirstName { get; set; }
        public String LastName { get; set; }
        public bool HighlightPerson { get; set; }
    }
}

自定义数据网格列

public class FormattableTextBoxColumn : DataGridTextBoxColumn
{
    public event FormatCellEventHandler SetCellFormat;

    protected override void Paint(Graphics g, Rectangle bounds, CurrencyManager source, int rowNum, Brush backBrush, Brush foreBrush, bool alignToRight)
    {
        DataGridFormatCellEventArgs e = new DataGridFormatCellEventArgs(rowNum, source);
        e.ForeBrush = foreBrush;
        e.BackBrush = backBrush;
        OnSetCellFormat(e);
        base.Paint(g, bounds, source, rowNum, e.BackBrush, e.ForeBrush, alignToRight);
    }

    private void OnSetCellFormat(DataGridFormatCellEventArgs e)
    {
        FormatCellEventHandler handler = SetCellFormat;

        if (handler != null)
            handler(this, e);
    }
}

您还需要此DataGridCellEventArgs.cs

public delegate void FormatCellEventHandler(object sender, DataGridFormatCellEventArgs e);

public class DataGridFormatCellEventArgs : EventArgs
{
    public int Row;
    public CurrencyManager Source;
    public Brush BackBrush;
    public Brush ForeBrush;

    public DataGridFormatCellEventArgs(int row, CurrencyManager manager)
    {
        this.Row = row;
        this.Source = manager;
    }
}

以下是您的示例项目:

DataGridTest.zip

答案 1 :(得分:0)

我没有和CF一起工作,但是我想我会把它扔出去......如果你可以访问单元格,那么这行不是NamingContainer吗?如果是这样,您可以向上钻取行并应用样式或使用CSS类添加属性。

相关问题