c#比较datagridview中的两列并格式化第三列

时间:2013-10-29 16:38:52

标签: c#

我在datagridview中有4列:HomeTeam,HomeScore,AwayScore和AwayTeam。

我想比较HomeScore和AwayScore列。如果HomeScore高于Away Score,HomeTeam必须大胆。请帮忙。

2 个答案:

答案 0 :(得分:0)

试试这个:

        DataGridViewCellStyle style = new DataGridViewCellStyle();
        style.Font = new Font(dataGridView1.Font, FontStyle.Bold);

        for (int i = 0; i==dataGridView1.Rows.Count; i++ )
            if ((int)dataGridView1.Rows[i].Cells[0].Value > (int)dataGridView1.Rows[i].Cells[3].Value)
        {
            dataGridView1.Rows[i].Cells[0].Style = style;
        }
        else if ((int)dataGridView1.Rows[i].Cells[0].Value < (int)dataGridView1.Rows[i].Cells[3].Value)
        {

            dataGridView1.Rows[i].Cells[3].Style = style;
        }

答案 1 :(得分:0)

这样做:

        private void Form1_Load(object sender, EventArgs e)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("HomeScore");
            dt.Columns.Add("AwayScore");
            dt.Columns.Add("AwayTeam");
            dt.Rows.Add(3, 1,"Everton");

            this.dataGridView1.DataSource = dt;

            this.dataGridView1.CellFormatting +=
                new DataGridViewCellFormattingEventHandler(dataGridView1_CellFormatting);
        }

        void dataGridView1_CellFormatting(object sender,DataGridViewCellFormattingEventArgs e)
        {
            if (e.RowIndex > -1 && e.ColumnIndex == dataGridView1.Columns["AwayTeam"].Index)
            {
                e.FormattingApplied = true;
                int home = Convert.ToInt32(dataGridView1["HomeScore", e.RowIndex].Value);
                int away = Convert.ToInt32(dataGridView1["AwayScore", e.RowIndex].Value);
                if (home > away)
                {
                    DataGridViewCellStyle style = new DataGridViewCellStyle();

                    style.Font = new Font(dataGridView1.Font, FontStyle.Bold);
                    e.CellStyle = style;

                }
            }
        }

这种方式每次更新主场比分或客场比分时,客场单元也会更新。