C语言
主页 > 软件编程 > C语言 >

C#开发WinForm根据条件改变DataGridView行颜色

2022-03-08 | 秩名 | 点击:

根据条件改变DataGridView行的颜色可以使用RowPrePaint事件。

示例程序界面如下:

示例程序代码如下:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

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;

        }

    }

}

原文链接:https://www.cnblogs.com/dotnet261010/p/8464343.html
相关文章
最新更新