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. 用容器部署Nexus 3作为Nuget和Docker的仓库

    1.准备docker-compose的配置文件 version: '3' services: nexus: image: 'sonatype/nexus3:3.42.0' container_name ...

  2. C++ //谓词 //一元谓词 //概念:返回bool类型的仿函数称为 谓词 //如果 operator()接受一个参数,那么叫做一元谓词 //如果 operator()接受 2 个参数,那么叫做一元谓词

    1 //谓词 2 //一元谓词 3 //概念:返回bool类型的仿函数称为 谓词 4 //如果 operator()接受一个参数,那么叫做一元谓词 5 //如果 operator()接受 2 个参数, ...

  3. kafka的数据同步原理ISR、ACK、LEO、HW

    1.数据可靠性保证,数据同步 为保证 producer 发送的数据,能可靠的发送到指定的 topic,topic 的每个 partition 收到 producer 发送的数据后,都需要向 produ ...

  4. 在vue3中使用openlayers3实现track轨迹动画

    网上太多资料代码,抄来抄去,而且版本也是v5.x版本的,部分API已经弃用 基础知识不多说,直接讲重点 三个关键变量 // 记录开始动画的时间 const startTime = ref(0); // ...

  5. immutable 不可改变的 mut ≈ to move = to change - 单词学习

    immutable im-不,非 + mut-改变 + -able. im 通 in able 有能力的 重点是 mut 的含义是 to change t 就是to mu 就是 change (*拉丁 ...

  6. 基于python的环境噪声监测报警系统实例解析

    一 系统简介 1.简介 该系统可以实时显示噪声量大小,并进行一段时间的噪声统计. 2.特性 实现噪声值的统计 实现了噪声显示 完整的主题和样式控制 多线程的运行模式 二 源码解析 1.串口db值获取: ...

  7. 基于python的PC电脑报警系统

    一 基本概念 1.这里实现了电脑的安全报警系统,假如有人不小心动了你的电脑,立即触发报警系统.报警是通过pc机的声卡播放报警信号. 2.该的基础是对python的pyxhook和wave库的合理应用. ...

  8. 基于泰凌微TLSR825x的物联网解决方案之ibeacon开发总结

    一 概念   iBeacon 是苹果公司2013年9月发布的移动设备用OS(iOS7)上配备的新功能.其工作方式是,配备有 低功耗蓝牙(BLE)通信功能的设备使用BLE技术向周围发送自己特有的ID,接 ...

  9. Hibernate之Criteria

      1,Criteria Hibernate 设计了 CriteriaSpecification 作为 Criteria 的父接口,下面提供了 Criteria和DetachedCriteria . ...

  10. socket本地通信服务端

    #include <stdio.h> #include <sys/socket.h> #include <arpa/inet.h> #include <str ...