DevExpress的GridControl控件可以从任何数据源绑定数据并进行增删查改等操作,和VS自带的dataGridView控件对比,GridControl控件可以实现更多自定义的功能,界面UI也更精美,今天我和大家分享一个Demo演示GridControl控件的增删查改操作!

首先,主界面由一个GridControl控件构成,可执行数据的增、删、查、改和导出操作,如图1所示:

图1-主界面(点击图片可放大)

实战演示:

1.主界面添加一个GridControl控件和一个Button,如图2所示:

图2-操作步骤1(点击图片可放大)

2.将GridControl控件的UseEmbeddedNavigator 属性设置为True,如图3所示:

图3-操作步骤2(点击图片可放大)

3.项目中添加System.ComponentModel.DataAnnotations引用,用于验证字段数据正确性,如图4所示:

图4-操作步骤3(点击图片可放大)

4.在初始化方法中添加gridControl控件的标题、顶部添加项、允许编辑和删除事件等,代码如下:

public Form1()
{
InitializeComponent();
 
//gridView1标题
gridView1.GroupPanelText = "深圳精品4S旗舰店订单管理:";
 
//gridView1顶部显示添加行
gridView1.OptionsView.NewItemRowPosition = NewItemRowPosition.Top;
 
//gridView1允许编辑
gridView1.OptionsBehavior.Editable = true;
 
//gridView1选中行后按快捷键 “Ctrl+Del” 删除
gridControl1.ProcessGridKey += (s, e) =>
{
if (e.KeyCode == Keys.Delete && e.Modifiers == Keys.Control)
{
if (XtraMessageBox.Show("是否删除选中行?", "删除行对话框", MessageBoxButtons.YesNo) !=
DialogResult.Yes)
return;
GridControl grid = s as GridControl;
GridView view = grid.FocusedView as GridView;
view.DeleteSelectedRows();
}
};
}

5.定义一个类用来进行字段属性设置并通知客户端,代码如下:

/// <summary>
/// 字段属性设置并验证字段属性数据的正确性,属性变更后向客户端发出属性值已更改的通知。
/// </summary>
public class Record : INotifyPropertyChanged
{
public Record()
{
}
int id;
[DisplayName("订单号")]
public int ID
{
get { return id; }
set
{
if (id != value)
{
id = value;
OnPropertyChanged();
}
}
}
 
string text;
[DisplayName("品牌")]
public string Brand
{
get { return text; }
set
{
if (text != value)
{
if (string.IsNullOrEmpty(value))
throw new Exception();
text = value;
OnPropertyChanged();
}
}
}
Nullable<decimal> val;
[DataType(DataType.Currency)]
[DisplayName("售价")]
public Nullable<decimal> Value
{
get { return val; }
set
{
if (val != value)
{
val = value;
OnPropertyChanged();
}
}
}
DateTime dt;
[DisplayName("交期")]
public DateTime RequiredDate
{
get { return dt; }
set
{
if (dt != value)
{
dt = value;
OnPropertyChanged();
}
}
}
bool state;
[DisplayName("完成")]
public bool Processed
{
get { return state; }
set
{
if (state != value)
{
state = value;
OnPropertyChanged();
}
}
}
 
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string propertyName = "")
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}

6.定义一个数据随机生成方法并传值到字段中,代码如下:

/// <summary>
/// 生成随机字段数据
/// </summary>
public class DataHelper
{
public static string[] brands = new string[] { "奔驰", "宝马", "奥迪", "大众",
"马自达", "雷克萨斯", "红旗" ,"路虎","丰田","本田","现代"};
 
public static BindingList<Record> GetData(int count)
{
BindingList<Record> records = new BindingList<Record>();
Random rnd = new Random();
for (int i = 0; i < count; i++)
{
int n = rnd.Next(10);
records.Add(new Record()
{
ID = i + 2020000,
Brand = brands[i % brands.Length],
RequiredDate = DateTime.Today.AddDays(n + 30),
Value = i % 2 == 0 ? (i + 1) * 123456 : i * 12345,
Processed = i % 2 == 0,
});
};
return records;
}
}

7.定义一个方法利用XtraPrinting导出GridControl中的信息并保存为Excel,代码如下:

/// <summary>
/// 导出dataGrid为Excle
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Btn_Output_Click(object sender, EventArgs e)
{
SaveFileDialog fileDialog = new SaveFileDialog();
fileDialog.Title = "导出Excel";
fileDialog.Filter = "Excel文件(*.xls)|*.xls";
DialogResult dialogResult = fileDialog.ShowDialog(this);
if (dialogResult == DialogResult.OK)
{
DevExpress.XtraPrinting.XlsExportOptions options = new
DevExpress.XtraPrinting.XlsExportOptions();
gridControl1.ExportToXls(fileDialog.FileName);
DevExpress.XtraEditors.XtraMessageBox.Show("保存成功!", "提示",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}

8.在Form_Load函数中给gridControl控件绑定数据并修改单元格外观,实现启动时自动加载数据,代码如下:

private void Form1_Load(object sender, EventArgs e)
{
//dataGrid自动在数据源中找到公共字段并创建列。
gridControl1.DataSource = DataHelper.GetData(10);
 
//创建一个ComboBox编辑器,在“品牌”列中显示可用的品牌。
RepositoryItemComboBox riComboBox = new RepositoryItemComboBox();
riComboBox.Items.AddRange(DataHelper.brands);
gridControl1.RepositoryItems.Add(riComboBox);
gridView1.Columns["Brand"].ColumnEdit = riComboBox;
 
//设置订单号列的外观颜色
GridColumn colID = gridView1.Columns["ID"];
colID.AppearanceCell.BackColor2 = Color.DarkGreen;
colID.AppearanceCell.BackColor = Color.LightGreen;
colID.AppearanceCell.ForeColor = Color.White;
 
//设置品牌列的外观颜色
GridColumn colCompanyName = gridView1.Columns["Brand"];
colCompanyName.AppearanceCell.BackColor = Color.DarkKhaki;
colCompanyName.AppearanceCell.ForeColor = Color.Black;
 
//设置交期列的外观颜色
GridColumn colRequiredDate = gridView1.Columns["RequiredDate"];
colRequiredDate.AppearanceCell.ForeColor = Color.Red;
}

代码全文:

using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Drawing;
using System.Runtime.CompilerServices;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.Grid;
 
namespace dataGrid
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
 
//gridView1标题
gridView1.GroupPanelText = "深圳精品4S旗舰店订单管理:";
 
//gridView1顶部显示添加行
gridView1.OptionsView.NewItemRowPosition = NewItemRowPosition.Top;
 
//gridView1允许编辑
gridView1.OptionsBehavior.Editable = true;
 
//gridView1选中行后按快捷键 “Ctrl+Del” 删除
gridControl1.ProcessGridKey += (s, e) =>
{
if (e.KeyCode == Keys.Delete && e.Modifiers == Keys.Control)
{
if (XtraMessageBox.Show("是否删除选中行?", "删除行对话框", MessageBoxButtons.YesNo) !=
DialogResult.Yes)
return;
GridControl grid = s as GridControl;
GridView view = grid.FocusedView as GridView;
view.DeleteSelectedRows();
}
};
}
 
/// <summary>
/// 字段属性设置并验证字段属性数据的正确性,属性变更后向客户端发出属性值已更改的通知。
/// </summary>
public class Record : INotifyPropertyChanged
{
public Record()
{
}
int id;
[DisplayName("订单号")]
public int ID
{
get { return id; }
set
{
if (id != value)
{
id = value;
OnPropertyChanged();
}
}
}
 
string text;
[DisplayName("品牌")]
public string Brand
{
get { return text; }
set
{
if (text != value)
{
if (string.IsNullOrEmpty(value))
throw new Exception();
text = value;
OnPropertyChanged();
}
}
}
Nullable<decimal> val;
[DataType(DataType.Currency)]
[DisplayName("售价")]
public Nullable<decimal> Value
{
get { return val; }
set
{
if (val != value)
{
val = value;
OnPropertyChanged();
}
}
}
DateTime dt;
[DisplayName("交期")]
public DateTime RequiredDate
{
get { return dt; }
set
{
if (dt != value)
{
dt = value;
OnPropertyChanged();
}
}
}
bool state;
[DisplayName("完成")]
public bool Processed
{
get { return state; }
set
{
if (state != value)
{
state = value;
OnPropertyChanged();
}
}
}
 
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string propertyName = "")
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
 
 
/// <summary>
/// 生成随机字段数据
/// </summary>
public class DataHelper
{
public static string[] brands = new string[] { "奔驰", "宝马", "奥迪", "大众",
"马自达", "雷克萨斯", "红旗" ,"路虎","丰田","本田","现代"};
 
public static BindingList<Record> GetData(int count)
{
BindingList<Record> records = new BindingList<Record>();
Random rnd = new Random();
for (int i = 0; i < count; i++)
{
int n = rnd.Next(10);
records.Add(new Record()
{
ID = i + 2020000,
Brand = brands[i % brands.Length],
RequiredDate = DateTime.Today.AddDays(n + 30),
Value = i % 2 == 0 ? (i + 1) * 123456 : i * 12345,
Processed = i % 2 == 0,
});
};
return records;
}
}
 
/// <summary>
/// 导出dataGrid为Excle
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Btn_Output_Click(object sender, EventArgs e)
{
SaveFileDialog fileDialog = new SaveFileDialog();
fileDialog.Title = "导出Excel";
fileDialog.Filter = "Excel文件(*.xls)|*.xls";
DialogResult dialogResult = fileDialog.ShowDialog(this);
if (dialogResult == DialogResult.OK)
{
DevExpress.XtraPrinting.XlsExportOptions options = new
DevExpress.XtraPrinting.XlsExportOptions();
gridControl1.ExportToXls(fileDialog.FileName);
DevExpress.XtraEditors.XtraMessageBox.Show("保存成功!", "提示",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
 
 
private void Form1_Load(object sender, EventArgs e)
{
//dataGrid自动在数据源中找到公共字段并创建列。
gridControl1.DataSource = DataHelper.GetData(10);
 
//创建一个ComboBox编辑器,在“品牌”列中显示可用的品牌。
RepositoryItemComboBox riComboBox = new RepositoryItemComboBox();
riComboBox.Items.AddRange(DataHelper.brands);
gridControl1.RepositoryItems.Add(riComboBox);
gridView1.Columns["Brand"].ColumnEdit = riComboBox;
 
//设置订单号列的外观颜色
GridColumn colID = gridView1.Columns["ID"];
colID.AppearanceCell.BackColor2 = Color.DarkGreen;
colID.AppearanceCell.BackColor = Color.LightGreen;
colID.AppearanceCell.ForeColor = Color.White;
 
//设置品牌列的外观颜色
GridColumn colCompanyName = gridView1.Columns["Brand"];
colCompanyName.AppearanceCell.BackColor = Color.DarkKhaki;
colCompanyName.AppearanceCell.ForeColor = Color.Black;
 
//设置交期列的外观颜色
GridColumn colRequiredDate = gridView1.Columns["RequiredDate"];
colRequiredDate.AppearanceCell.ForeColor = Color.Red;
}
 
private void Button1_Click(object sender, EventArgs e)
{
//欢迎访问大博客,阅读更多编程实战案例!
System.Diagnostics.Process.Start("https://www.daboke.com");
}
 
private void Button2_Click(object sender, EventArgs e)
{
//原文链接!
System.Diagnostics.Process.Start("https://www.daboke.com/devexpress/gridcontrol.html");
}
 
private void Button3_Click(object sender, EventArgs e)
{
//欢迎访问我的B站频道-编程自修室,观看更多C#编程实战视频!
System.Diagnostics.Process.Start("https://space.bilibili.com/580719958");
}
}
}

原文链接:https://www.daboke.com/devexpress/gridcontrol.html

B站up主-编程自修室:https://space.bilibili.com/580719958

源码下载:dataGrid

C# DevExpress下GridControl控件的增删查改的更多相关文章

  1. DevExpress之GridControl控件小知识

    DevExpress之GridControl控件小知识 一.当代码中的DataTable中有建数据关系时,DevExpress 的 GridControl 会自动增加一个子视图 .列名也就是子表的字段 ...

  2. DevExpress的GridControl控件更新數據問題解決辦法

    開發WPF程序時,使用Devexpress的GridControl控件用ItemSource綁定數據,在頁面進行編輯時,當屬性繼承INotifyPropertyChanged接口時會同步更新後臺數據. ...

  3. C# DevExpress中GridControl控件的基本属性设置和使用方法

    1.GridControl隐藏GroupPanel(主面板) 隐藏:鼠标单击Run Designer-OptionsView-ShowGroupPanel=False; 修改:鼠标单击Run Desi ...

  4. DevExpress的GridControl控件设置自定义显示方法

    比如要显示性别为字符串,数据库中保存为数值(1:男,2:女,3:未知). 方法一: 点击控件上的"Run Designer"按钮,进入设计界面. 选择“Columns", ...

  5. DevExpress中GridControl控件焦点改变时触发事件

    FocusedRowObjectChanged 事件.可以在焦点改变一行的时候触发对应的事件. 做一个记录 大家如果有问题可以 Console.WriteLine("加群"+&qu ...

  6. DevExpress控件的GridControl控件小结

    DevExpress控件的GridControl控件小结 (由于开始使用DevExpress控件了,所以要点滴的记录一下) 1.DevExpress控件组中的GridControl控件不能使横向滚动条 ...

  7. DevExpress控件GridView挂下拉控件无法对上值

    下拉控件使用RepositoryItemLookUpEdit,加入如下事件进行处理. repositoryItemLookUpEdit1.CustomDisplayText += new DevExp ...

  8. 关于Devexpress15.2中GridControl控件选择字段ColumnEdit下拉时间设置

    效果:点击表格GridControl控件中的列,可以显示日期和时间.时间可以手动修改.(绑定日期格式的字段) 设置步骤:1.点击时间字段列表设置ColumnEdit-New-选择DateEdit出现r ...

  9. DevExpress GridControl控件行内新增、编辑、删除添加选择框

    以下为内容以图片居多1234表示点击顺序 先新增一行 操作和新增数据行一样 打开ColumnEdit  选择new ButtenEdit  new上方会出现一个系统命名的button 命名可以更改必须 ...

  10. Devexpress使用之:GridControl控件

    Devexpress使用之:GridControl控件 Devexpress系列控件功能很强大,使用起来也不太容易,我也是边摸索边使用,如果有时间我会把常用控件的使用方法整理出来的. using Sy ...

随机推荐

  1. mysql常用语句(持续更新)

    查询数据库中各表数量 select table_name,table_rows from information_schema.tables where TABLE_SCHEMA = 'miot' o ...

  2. Java 类的内部成员之五:内部类

    1 package com.bytezreo.innerclass; 2 3 /** 4 * 5 * @Description 类的内部成员之五:内部类 6 * @author Bytezero·zh ...

  3. 英语单词组件- 单词在句子中,上面显示中文下面显示音标 css样式

    原先效果: 改进demo效果 优化点 音标长度超出,或者中文超出,总宽度会按照最长的走 居中显示 再次优化 line-height: 22px; 加入这个 对齐中间行(字号大小会让绝对上下高度,对不齐 ...

  4. C++学习笔记之基础语法

    目录 基础语法 switch和if区别 枚举定义及作用域 结构体数据耐齐--缺省对齐原则 函数重载overload与C++Name Mangling 指向函数的指针与返回指针的函数 基础语法 swit ...

  5. Nginx的负载均衡策略(4+2)

    Nginx的负载均衡策略主要包括以下几种: 轮询(Round Robin):每个请求按时间顺序逐一分配到不同的后端服务器,如果后端服务器down掉,能自动剔除.这是Nginx的默认策略,适合服务器配置 ...

  6. Java/Kotlin 密码复杂规则校验

    原文地址: Java/Kotlin 密码复杂度校验 | Stars-One的杂货小窝 每次有那个密码复杂校验,不会写正则表达式,每次都去搜,但有时候校验的条件又是奇奇怪怪的,百度都搜不到 找到了个代码 ...

  7. 通达信金融终端解锁Level-2功能 续(202307)

    外挂方式,不修改原程序.解锁Level-2 逐笔分析.对"非法访问"Say NO! LEVEL2逐笔分析破解后,仍然被防调试. 竞价分析,实时资金示例. 逆向通达信Level-2 ...

  8. jenkins安装和基本使用

    参考:https://zhuanlan.zhihu.com/p/56037782(安装) https://gitee.com/oschina/Gitee-Jenkins-Plugin/(使用) htt ...

  9. 对TCP/IP协议的理解

    话说两台电脑要通讯就必须遵守共同的规则,就好比两个人要沟通就必须使用共同的语言一样.一个只懂英语的人,和一个只懂中文的人由于没有共同的语言(规则)就没办法沟通.两台电脑之间进行通讯所共同遵守的规则,就 ...

  10. Java博客大汇总

    目录介绍 01.Java基础[30篇] 02.面向对象[15篇] 03.数据结构[27篇] 04.IO流知识[11篇] 05.线程进程[9篇] 06.虚拟机[12篇] 07.类的加载[7篇] 08.反 ...