溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

C#開發WinForm中怎么根據條件改變DataGridView行顏色

發布時間:2022-03-08 09:04:24 來源:億速云 閱讀:335 作者:iii 欄目:開發技術

本文小編為大家詳細介紹“C#開發WinForm中怎么根據條件改變DataGridView行顏色”,內容詳細,步驟清晰,細節處理妥當,希望這篇“C#開發WinForm中怎么根據條件改變DataGridView行顏色”文章能幫助大家解決疑惑,下面跟著小編的思路慢慢深入,一起來學習新知識吧。

根據條件改變DataGridView行的顏色可以使用RowPrePaint事件。

示例程序界面如下:

C#開發WinForm中怎么根據條件改變DataGridView行顏色

示例程序代碼如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Configuration;
using System.Data.SqlClient;

namespace DgvChangeColor
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        string strCon = ConfigurationManager.ConnectionStrings["DbConnection"].ConnectionString;
        private void Form1_Load(object sender, EventArgs e)
        {
            DataTable dt = GetDataSource();
            this.DgvColor.DataSource = dt;
        }

        private void DgvColor_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
        {
            if (e.RowIndex >= DgvColor.Rows.Count - 1)
            {
                return;
            }
            DataGridViewRow dr = (sender as DataGridView).Rows[e.RowIndex];

            if (dr.Cells["項目代碼"].Value.ToString().Trim().Equals("ACAC0001"))
            {
                // 設置單元格的背景色
                dr.DefaultCellStyle.BackColor = Color.Yellow;
                // 設置單元格的前景色
                dr.DefaultCellStyle.ForeColor = Color.Black;
            }
            else
            {
                dr.DefaultCellStyle.BackColor = Color.Blue;
                dr.DefaultCellStyle.ForeColor = Color.White;
            }
        }

        private DataTable GetDataSource()
        {
            DataTable dt = new DataTable();
            SqlConnection conn = new SqlConnection(strCon);
            string strSQL = "SELECT XIANGMUCDDM AS '項目代碼',XIANGMUMC AS '項目名稱', DANJIA AS '單價',SHULIANG AS '數量' FROM InPatientBillDt WHERE 就診ID='225600'";
            SqlCommand cmd = new SqlCommand(strSQL, conn);
            SqlDataAdapter adapter = new SqlDataAdapter();
            adapter.SelectCommand = cmd;
            try
            {
                conn.Open();
                adapter.Fill(dt);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                conn.Close();
            }
            return dt;
        }
    }
}

讀到這里,這篇“C#開發WinForm中怎么根據條件改變DataGridView行顏色”文章已經介紹完畢,想要掌握這篇文章的知識點還需要大家自己動手實踐使用過才能領會,如果想了解更多相關內容的文章,歡迎關注億速云行業資訊頻道。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女