基本信息
源码名称:DevExpress下GridControl控件的增删查改
源码大小:29.40M
文件格式:.zip
开发语言:C#
更新时间:2020-06-21
   源码介绍

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


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