1

我一直在尝试更改 Compact Framework DataGrid 中一行的背景颜色,但收效甚微,因为 .NET CF 上的 DataGrid 与其 Windows 窗体对应物相比受到限制。我实现目标的唯一一点成功是我现在能够根据其值更改单个单元格的背景颜色。我无法操纵从谷歌搜索得到的代码,因为我在 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"];
            }
        }
    }

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

4

2 回答 2

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;
    }
}

这是一个示例项目:

数据网格测试.zip

于 2012-10-19T22:41:40.150 回答
0

我没有和 CF 合作过,但我想我会把它扔在那里......如果你可以访问单元格,那行不是NamingContainer吗?如果是这样,您可以向上钻取该行并应用样式或添加带有 CSS 类的属性。

于 2012-10-16T06:43:21.667 回答