其他分享
首页 > 其他分享> > Dev中实现给GridControl下的GridView表格修改指定行、列的背景颜色和获取选择行的信息

Dev中实现给GridControl下的GridView表格修改指定行、列的背景颜色和获取选择行的信息

作者:互联网

一、实现效果

①修改GridView的标题背景颜色;

②修改选中行的背景颜色;

③修改指定行的背景颜色;

④修改指定列的背景颜色;

⑤修改指定单元格的背景颜色;

⑥获取GridView表格选中行的数据信息;

⑦获取GridView的标题头名称、字段;

⑧修改GridView的标题头名称;

二、实现核心

/***
*	Title:"Winfrom" 项目
*		主题:GridControl帮助类
*	Description:
*		功能:
*		    0、官网:https://docs.devexpress.com/WindowsForms/115548/controls-and-libraries/data-grid/appearance-and-conditional-formatting
*		    1、设置表格标题背景颜色
*		    2、设置选中行颜色
*		    3、设置奇偶行背景颜色
*		    4、设置表格指定行列的背景色
*		    5、获取到GridView的所有字段
*		    6、获取到GridView的所有备注名称
*		    7、修改表格指定的标题头名称
*		    8、给GridControl组件填充内容
*	Date:2021
*	Version:0.1版本
*	Author:Coffee
*	Modify Recoder:
*/

using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.Grid;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Utils
{
    class GridControlHelper
    {

        /// <summary>
        /// 设置表格标题背景颜色
        /// </summary>
        /// <param name="gridView">gridView组件</param>
        /// <param name="columnIndex">表格列索引</param>
        /// <param name="color">颜色</param>
        public static void SetGridViewHeaderBackColor(GridView gridView,
            int columnIndex, Color color)
        {
            if (gridView != null && gridView.Columns.Count>0 && columnIndex >= 0)
            {
                gridView.Columns[columnIndex].AppearanceHeader.BackColor = color;
            }
        }

        /// <summary>
        /// 设置表格标题背景颜色
        /// </summary>
        /// <param name="gridView">gridView组件</param>
        /// <param name="columnIndex">表格列索引</param>
        /// <param name="color">颜色</param>
        public static void SetGridViewHeaderBackColor(GridView gridView,
            string columnName, Color color)
        {
            if (gridView != null && gridView.Columns.Count > 0 && !string.IsNullOrEmpty(columnName))
            {
                gridView.Columns[columnName].AppearanceHeader.BackColor = color;
            }
        }

        /// <summary>
        /// 设置选中行颜色
        /// </summary>
        /// <param name="gridView">GridView组件</param>
        public static void SetSelectedRowColor(GridView gridView, Color selectedRowColor, Color focusedColor)
        {
            gridView.Appearance.SelectedRow.BackColor = selectedRowColor;
            gridView.Appearance.FocusedRow.BackColor = focusedColor;
        }

        /// <summary>
        /// 设置奇偶行背景颜色,统一风格
        /// </summary>
        /// <param name="gridView">gridView组件</param>
        /// <param name="oddColor">奇数行颜色</param>
        /// <param name="evenColor">偶数行颜色</param>
        public static void SetOddEvenRowColor(GridView gridView, Color oddColor, Color evenColor)
        {
            gridView.Appearance.OddRow.BackColor = oddColor;
            gridView.Appearance.EvenRow.BackColor = evenColor;
            gridView.OptionsView.EnableAppearanceOddRow = true;
            gridView.OptionsView.EnableAppearanceEvenRow = true;
        }

        /// <summary>
        /// 设置表格指定行列的背景色
        /// </summary>
        /// <param name="gridView">gridView组件</param>
        /// <param name="columnIndex">列索引</param>
        /// <param name="backColor">列的背景颜色1</param>
        /// <param name="backColor2">列的背景颜色2</param>
        /// <param name="foreColor">聚焦时颜色</param>
        public static void SetGridColumnBackColor(GridView gridView,int columnIndex, 
            Color backColor, Color backColor2, Color foreColor)
        {
            if (gridView != null && columnIndex >= 0)
            {
                GridColumn colID = gridView.Columns[columnIndex];
                colID.AppearanceCell.BackColor = backColor;
                colID.AppearanceCell.BackColor2 = backColor2;
                colID.AppearanceCell.ForeColor = foreColor;

            }
        }

        /// <summary>
        /// 设置表格指定行列的背景色
        /// </summary>
        /// <param name="gridView">gridView组件</param>
        /// <param name="columnIndex">列索引</param>
        /// <param name="backColor">列的背景颜色1</param>
        /// <param name="backColor2">列的背景颜色2</param>
        /// <param name="foreColor">聚焦时颜色</param>
        public static void SetGridColumnBackColor(GridView gridView, string columnFieldName,
            Color backColor, Color backColor2, Color foreColor)
        {
            if (gridView != null && !string.IsNullOrEmpty(columnFieldName))
            {
                GridColumn colID = gridView.Columns[columnFieldName];
                colID.AppearanceCell.BackColor = backColor;
                colID.AppearanceCell.BackColor2 = backColor2;
                colID.AppearanceCell.ForeColor = foreColor;

            }
        }


        /// <summary>
        /// 获取到GridView的所有字段
        /// </summary>
        /// <param name="gridView">GridView组件</param>
        /// <returns></returns>
        public static List<string> GetAllFieldOfGrirdView(GridView gridView)
        {
            List<string> tmpList = new List<string>();
            if (gridView != null && gridView.Columns.Count > 0)
            {
                int count = gridView.Columns.Count;
                for (int i = 0; i < count; i++)
                {
                    tmpList.Add(gridView.Columns[i].FieldName);
                }
            }

            return tmpList;
        }

        /// <summary>
        /// 获取到GridView的所有备注名称
        /// </summary>
        /// <param name="gridView">GridView组件</param>
        /// <returns></returns>
        public static List<string> GetAllCaptionOfGrirdView(GridView gridView)
        {
            List<string> tmpList = new List<string>();
            if (gridView != null && gridView.Columns.Count > 0)
            {
                int count = gridView.Columns.Count;
                for (int i = 0; i < count; i++)
                {
                    tmpList.Add(gridView.Columns[i].Caption);
                }
            }

            return tmpList;
        }

        /// <summary>
        /// 修改表格指定的标题头名称
        /// </summary>
        /// <param name="gridView">GirdView表格</param>
        /// <param name="columnIndex">需要修改列标题名称的索引</param>
        /// <param name="headerName">修改后的列标题的名称</param>
        public static void ModifyGridViewTitleHeader(GridView gridView, int columnIndex, string headerName)
        {
            if (gridView != null && columnIndex > 0 && !string.IsNullOrEmpty(headerName))
            {
                gridView.Columns[columnIndex].Caption = headerName;
            }
        }

        /// <summary>
        /// 修改表格指定的标题头名称
        /// </summary>
        /// <param name="gridView">GirdView表格</param>
        /// <param name="columnName">需要修改列标题名称的字段名</param>
        /// <param name="headerName">修改后的列标题的名称</param>
        public static void ModifyGridViewTitleHeader(GridView gridView, string columnName, string headerName)
        {
            if (gridView != null && !string.IsNullOrEmpty(columnName) && !string.IsNullOrEmpty(headerName))
            {
                gridView.Columns[columnName].Caption = headerName;
            }
        }

        /// <summary>
        /// 给GridControl组件填充内容
        /// </summary>
        /// <param name="gridControl">gridControl组件名称</param>
        /// <param name="gridView">gridView组件名称</param>
        /// <param name="dataTable">dataTable数据</param>
        public static void FillDatasToGridControl(GridControl gridControl, GridView gridView, DataTable dataTable)
        {
            gridControl.DataSource = dataTable;
            gridControl.Refresh();
            gridView.BestFitColumns();
        }

    }//Class_end

}

三、使用方法

3.1、修改背景颜色使用GirdView的【CustomDrawCell】事件

3.2、获取选中行的信息使用GirdView的【FocusedRowChanged】事件

using DevExpress.Utils;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.Base;
using DevExpress.XtraGrid.Views.Grid;
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 Utils;

namespace Dev_WinfromTest
{
    public partial class GridForm : DevExpress.XtraEditors.XtraForm
    {
        public GridForm()
        {
            InitializeComponent();
        }

        private void GridForm_Load(object sender, EventArgs e)
        {
            GridSettings();
            LoadDatasToGrid();
            GridControlHelper.SetSelectedRowColor(gridView1, Color.Yellow, Color.Orange);

        }


        //设置表格
        private void GridSettings()
        {
            //设置表格数据是否可编辑
            gridView1.OptionsBehavior.Editable = true;
            gridView1.OptionsBehavior.ReadOnly = true;
        }

        private void gridView1_RowStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowStyleEventArgs e)
        {

        }

       


        /// <summary>
        /// 加载数据到表格中
        /// </summary>
        /// <returns></returns>
        private void LoadDatasToGrid()
        {
            //模拟数据
            List<PeopleInfo> peopeoInfos = new List<PeopleInfo>()
            {
                new PeopleInfo{ Id="SL009",Name="谭维维",Age=23,Sex="男",Email="3625783421@qq.com",Address="测试地址1",Work="产品经理"},
                new PeopleInfo{ Id="SL008",Name="司一航",Age=22,Sex="男",Email="3625783422@qq.com",Address="测试地址2",Work="销售专员"},
                new PeopleInfo{ Id="SL007",Name="周  倩",Age=25,Sex="女",Email="3625783423@qq.com",Address="测试地址3",Work="技术主管"},
                new PeopleInfo{ Id="SL006",Name="王一星",Age=21,Sex="男",Email="3625783424@qq.com",Address="测试地址4",Work="设备主管"},
                new PeopleInfo{ Id="SL005",Name="策俊逸",Age=24,Sex="男",Email="3625783425@qq.com",Address="测试地址5",Work="项目经理"},
                new PeopleInfo{ Id="SL004",Name="周  茜",Age=22,Sex="女",Email="3625783426@qq.com",Address="测试地址6",Work="人资专员"},
                new PeopleInfo{ Id="SL003",Name="司王成",Age=26,Sex="男",Email="3625783427@qq.com",Address="测试地址7",Work="车间主任"},
                new PeopleInfo{ Id="SL002",Name="杨思凡",Age=24,Sex="男",Email="3625783428@qq.com",Address="测试地址8",Work="生产员工"},
                new PeopleInfo{ Id="SL001",Name="策一方",Age=23,Sex="男",Email="3625783429@qq.com",Address="测试地址9",Work="售后员工"},
             };

            DataTable dt = DataTableHelper.ListToDataTable(peopeoInfos);

            gridControl1.DataSource = dt;
        }
            
        //修改表格的背景颜色
        private void gridView1_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e)
        {
            //修改指定单元格的颜色
            if (modifyCellBackColor && e.Column.FieldName == "Work")
            {
                string strName = gridView1.GetRowCellDisplayText(e.RowHandle, gridView1.Columns["Work"]);
                //实现修改指定格的颜色
                if (strName.Equals("技术主管"))
                {
                    e.Appearance.BackColor = Color.SkyBlue;
                    e.Appearance.BackColor2 = Color.LightCyan;
                }
               
            }

            //修改指定单元格的颜色
            if (modifyColumnBackColor && e.Column.FieldName == "Sex")
            {
                string strName = gridView1.GetRowCellDisplayText(e.RowHandle, gridView1.Columns["Sex"]);
                //实现修改指定列的颜色
                if (!string.IsNullOrEmpty(strName))
                {
                    e.Appearance.BackColor = Color.OrangeRed;
                }
               
            }


            DataRow dr = gridView1.GetDataRow(e.RowHandle);
            if (dr != null)
            {
                //修改指定值对应行的背景颜色
                if (modifySingleRowBackColor && dr["Work"].ToString() == "产品经理")
                {
                    e.Appearance.BackColor = Color.SkyBlue;
                }

                //修改指定行背景颜色
                if (modifyMutiRowBackColor && e.RowHandle >= 6 && e.RowHandle <= 8)
                {
                    e.Appearance.BackColor = Color.Pink;
                }

            }


            gridView1.RefreshData();
        }

        #region   修改背景
        private bool modifyCellBackColor = false;
        private bool modifyColumnBackColor = false;
        private bool modifySingleRowBackColor = false;
        private bool modifyMutiRowBackColor = false;

        //修改标题头背景颜色
        private void simpleButton5_Click(object sender, EventArgs e)
        {
            //设置标题头背景颜色
            GridControlHelper.SetGridViewHeaderBackColor(gridView1, 0, Color.BlueViolet);
            GridControlHelper.SetGridViewHeaderBackColor(gridView1, 3, Color.OrangeRed);
            GridControlHelper.SetGridViewHeaderBackColor(gridView1, 5, Color.LightGreen);


            GridControlHelper.SetGridViewHeaderBackColor(gridView1, "Name", Color.BlueViolet);
            GridControlHelper.SetGridViewHeaderBackColor(gridView1, "Email", Color.OrangeRed);
            GridControlHelper.SetGridViewHeaderBackColor(gridView1, "Work", Color.LightGreen);

        }

        //修改指定单元格背景
        private void simpleButton1_Click(object sender, EventArgs e)
        {
            modifyCellBackColor = true;
            modifyColumnBackColor = false;
            modifySingleRowBackColor = false;
            modifyMutiRowBackColor = false;
        }

        //修改指定列背景
        private void simpleButton2_Click(object sender, EventArgs e)
        {
            modifyCellBackColor = false;
            modifyColumnBackColor = true;
            modifySingleRowBackColor = false;
            modifyMutiRowBackColor = false;

            GridControlHelper.SetGridColumnBackColor(gridView1,2,Color.SkyBlue,Color.DeepPink,Color.Yellow);
        }




        //修改指定行背景
        private void simpleButton3_Click(object sender, EventArgs e)
        {
            modifyCellBackColor = false;
            modifyColumnBackColor = false;
            modifySingleRowBackColor = true;
            modifyMutiRowBackColor = false;
        }

        //修改多行背景
        private void simpleButton4_Click(object sender, EventArgs e)
        {
            modifyCellBackColor = false;
            modifyColumnBackColor = false;
            modifySingleRowBackColor = false;
            modifyMutiRowBackColor = true;
        }


        #endregion

        private void gridView1_ShownEditor(object sender, EventArgs e)
        {
            //修改选中的单元格颜色
            gridView1.ActiveEditor.BackColor = Color.GreenYellow;
        }

        //设置表格的奇偶行颜色
        private void simpleButton6_Click(object sender, EventArgs e)
        {
            
            GridControlHelper.SetOddEvenRowColor(gridView1,Color.LightSkyBlue,Color.Aqua);
        }
            
        //获取选中行的信息
        private void gridView1_RowClick(object sender, RowClickEventArgs e)
        {

            //当前选定行
            int i = this.gridView1.FocusedRowHandle;
            //选中行,列名为name的值
            gridView1.GetRowCellDisplayText(i, gridView1.Columns["name"]);
            if (e.Button == MouseButtons.Left)
            {
                labelControl1.Text="按下鼠标左键";
            }

            if (e.Button == MouseButtons.Right)
            {
                labelControl1.Text = "按下鼠标右键";
            }

            if (e.Clicks == 1)
            {
                labelControl1.Text = "单击";
            }
            if (e.Clicks == 2)
            {
                labelControl1.Text = "双击";
            }

        }

        private void gridView1_RowCellClick(object sender, RowCellClickEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                labelControl1.Text = "按下鼠标左键2";
            }

            if (e.Button == MouseButtons.Right)
            {
                labelControl1.Text = "按下鼠标右键2";
            }

            if (e.Clicks == 1)
            {
                labelControl1.Text = "单击2";
            }
            if (e.Clicks == 2)
            {
                labelControl1.Text = "双击2";
            }
        }

        private void gridView1_MouseDown(object sender, MouseEventArgs e)
        {
            //if (e.Button == MouseButtons.Left)
            //{
            //    labelControl1.Text = "按下鼠标左键3";
               
            //}

            //if (e.Button == MouseButtons.Right)
            //{
            //    labelControl1.Text = "按下鼠标右键3";
            //}

           

        }

        //获取选中行的数据(常用)
        private void gridView1_FocusedRowChanged(object sender, FocusedRowChangedEventArgs e)
        {
            labelControl1.Text = "";
            for (int i = 0; i < gridView1.Columns.Count; i++)
            {
                int[] selectRow = gridView1.GetSelectedRows();
                //获取到当前行的所有数据
                string str = gridView1.GetDataRow(selectRow[0])[gridView1.Columns[i].FieldName].ToString();
                labelControl1.Text += "   " + str;
            }
        }

        //获取表格的所有标题字段
        private void simpleButton7_Click(object sender, EventArgs e)
        {
            List<string> tmpFieldlist = GridControlHelper.GetAllFieldOfGrirdView(gridView1);
            string tmpStr = null;
            foreach (var item in tmpFieldlist)
            {
                tmpStr += " " + item;
            }
            labelControl1.Text = tmpStr;

        }

        //获取表格的所有标题名称
        private void simpleButton8_Click(object sender, EventArgs e)
        {
            List<string> tmpCaptionlist = GridControlHelper.GetAllCaptionOfGrirdView(gridView1);
            string tmpStr = null;
            foreach (var item in tmpCaptionlist)
            {
                tmpStr += " " + item;
            }
            labelControl1.Text = tmpStr;
        }

        //修改标题标题头名称
        private void simpleButton9_Click(object sender, EventArgs e)
        {
            GridControlHelper.ModifyGridViewTitleHeader(gridView1,2,"修改年龄标题名称");

            GridControlHelper.ModifyGridViewTitleHeader(gridView1, "Email", "修改邮箱标题名称");
        }
    }//Class_end

    //人员信息模型类
    public class PeopleInfo
    {
        public string Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
        public string Sex { get; set; }
        public string Email { get; set; }
        public string Address { get; set; }
        public string Work { get; set; }
    }
}

标签:gridView,string,Dev,GridView,using,GridControl,public,Columns
来源: https://blog.csdn.net/xiaochenXIHUA/article/details/120146950