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


DevExpress的GridControl控件可以從任何數據源綁定數據並進行增刪查改等操作,和VS自帶的dataGridView控件對比,GridControl控件可以實現更多自定義的功能,界面UI也更精美,今天我和大家分享一個Demo演示GridControl控件的增刪查改操作!

首先,主界面由一個GridControl控件構成,可執行數據的增、刪、查、改和導出操作,如圖1所示:

interface

圖1-主界面(點擊圖片可放大)

實戰演示:

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

guide1

圖2-操作步驟1(點擊圖片可放大)

2.將GridControl控件的UseEmbeddedNavigator 屬性設置為True,如圖3所示:

guide2

圖3-操作步驟2(點擊圖片可放大)

3.項目中添加System.ComponentModel.DataAnnotations引用,用於驗證字段數據正確性,如圖4所示:

guide3

圖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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM