• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C#DevExpress下GridControl控件的增删查改

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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);

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C#自定义控件的创建发布时间:2022-07-13
下一篇:
C#字符串、数组和List的截取和转换发布时间:2022-07-13
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap