在一个项目中,我遇到这样一个问题: 数据库字段只存储了一个字典ID1,在DataGrid中显示时,需要用相应的字典Value1来代替字典ID1显示.解决这个问题一般有两个方法:
方法1:  数据库查询Sql脚本直接把相应的字典Value1值查询出来.
方法2: 在显示DataGrid时,把相应的字典ID1转换成字典Value1显示.

关于方法1, 实现相对简单但是不灵活,并且我们采用的是强类型的DataSet,不想经常修改强类型Dataset的定义
关于方法2, 实现上相对复杂一些但是比较灵活,也不用破坏已定义的强类型DataSet.

于是我就决定采用方法二,上网也找了不少资料,终于在codeproejct找到一篇比较符合我需求的文章,我的实现逻辑如下:在创建Datagrid的column时,对于需要替换的column:Dict1用自定义的LookUpColumn来代替, 设置LookupColumn的Datasource DispalyMember及ValueMember,当Dataset中相应字段的值与LookupColumn的Datasource的ValueMember值相匹配时,显示相应的DispalyMember值.具体代码如下:

   DataGridLookupColumn lcolumnex = new DataGridLookupColumn(); 
   lcolumnex.MappingName = "Dict1"; 
   lcolumnex.HeaderText = lcolumnex.MappingName;   
   lcolumnex.comboBox.ValueMember = "DictID"; 
   lcolumnex.comboBox.DisplayMember = "DictValue"; 
   lcolumnex.Width = 80; 
   lcolumnex.comboBox.DataSource = CommonValue.GetDictList();//返回Dict结构(有DictID,DictValue属性)组成的一个ArrayList 
   lTableStyle.GridColumnStyles.Add(lcolumnex); 

具体的DataGridLookupColumn类实现代码如下:

/**//*本代码原稿由http://www.codeproject.com/cs/miscctrl/RenDataGridComboBoxColumn.asp获取,并做了相应的改动 by Zendyhu
*/
DataGridLookupColumn#region DataGridLookupColumn
    //**********************************************************************************************
    //    DataGridLookupColumn
    //**********************************************************************************************
    public class DataGridLookupColumn : DataGridColumnStyle 
    { //DataGridLookupColumn {
        private    DataGridComboBox    combobox;
        private    bool                    edit;

        //-------------------------------------------------------------------------------------------
        //    Constructors and destructors
        //-------------------------------------------------------------------------------------------
        public DataGridLookupColumn() 
        {
            combobox                                        = new DataGridComboBox();
            combobox.Visible                            = false;
            combobox.DropDownStyle                    = ComboBoxStyle.DropDownList;
            combobox.Leave                                += new EventHandler(ComboHide);
            combobox.SelectionChangeCommitted    += new EventHandler(ComboStartEditing);
            edit                                            = false;
        } // DataGridLookupColumn

        //-------------------------------------------------------------------------------------------
        //    Properties
        //-------------------------------------------------------------------------------------------
        public ComboBox comboBox 
        {
            get 
            {
                return combobox;
            }
        } // comboBox

        //-------------------------------------------------------------------------------------------
        //    ComboBox event handlers
        //-------------------------------------------------------------------------------------------
        private void ComboHide(object sender, EventArgs e) 
        {
            // When the ComboBox looses focus, then simply hide it.
            combobox.Hide();
        } // ComboHide

        private void ComboStartEditing(object sender, EventArgs e) 
        {
            // Enter edit mode.
            edit = true;
            base.ColumnStartedEditing((Control)sender);
        } // ComboStartEditing

        //-------------------------------------------------------------------------------------------
        //    Override DataGridColumnStyle
        //-------------------------------------------------------------------------------------------
        protected override void SetDataGridInColumn(DataGrid value) 
        {
            // Add the ComboBox to the DataGrids controls collection.
            // This ensures correct DataGrid scrolling.
            value.Controls.Add(combobox);
            base.SetDataGridInColumn(value);
        } // SetDataGridInColumn

        protected override void Abort(int rowNum) 
        {
            // Abort edit mode, discard changes and hide the ComboBox.
            edit = false;
            Invalidate();
            combobox.Hide();
        } // Abort

        protected override void Edit(System.Windows.Forms.CurrencyManager source, int rowNum, System.Drawing.Rectangle bounds, bool readOnly, string instantText, bool cellIsVisible) 
        {
            // Setup the ComboBox for action.
            // This includes positioning the ComboBox and showing it.
            // Also select the correct item in the ComboBox before it is shown.
            combobox.Parent            = this.DataGridTableStyle.DataGrid;
            combobox.Bounds            = bounds;
            combobox.Size                = new Size(this.Width, this.comboBox.Height);
            comboBox.SelectedValue    = base.GetColumnValueAtRow(source, rowNum).ToString();
            combobox.Visible            = (cellIsVisible == true) && (readOnly == false);
            combobox.BringToFront();
            combobox.Focus();    
        } // Edit

        protected override bool Commit(System.Windows.Forms.CurrencyManager source, int rowNum) 
        {
            // Commit the selected value from the ComboBox to the DataGrid.
            if (edit == true) 
            {
                edit = false;
                this.SetColumnValueAtRow(source, rowNum, combobox.SelectedValue);
            }

            return true;
        } // Commit

        protected override object GetColumnValueAtRow(System.Windows.Forms.CurrencyManager source, int rowNum) 
        {
            // Return the display text associated with the data, insted of the
            // data from the DataGrid datasource.
            return combobox.GetDisplayText(base.GetColumnValueAtRow(source, rowNum));
        } // GetColumnValueAtRow

        protected override void SetColumnValueAtRow(CurrencyManager source, int rowNum, object value) 
        {
            // Save the data (value) to the DataGrid datasource.
            // I try a few different types, because I often uses GUIDs as keys in my
            // data.

            // String.
            try 
            {
                base.SetColumnValueAtRow(source, rowNum, value.ToString());
                return;
            } 
            catch {}

            // Guid.
            try 
            {
                base.SetColumnValueAtRow(source, rowNum, new Guid(value.ToString()));
                return;
            } 
            catch {}

            // Object (default).
            base.SetColumnValueAtRow(source, rowNum, value);
        } // SetColumnValueAtRow

        protected override int GetMinimumHeight() 
        {
            // Return the ComboBox preferred height, plus a few pixels.
            return combobox.PreferredHeight;
        } // GetMinimumHeight
        
        protected override int GetPreferredHeight(Graphics g, object val) 
        {
            // Return the font height, plus a few pixels.
            return FontHeight + 2;
        } // GetPreferredHeight

        protected override Size GetPreferredSize(Graphics g, object val) 
        {
            // Return the preferred width.
            // Iterate through all display texts in the dropdown, and measure each
            // text width.
            int        widest        = 0;
            SizeF        stringSize    = new SizeF(0, 0);
            foreach (string text in combobox.GetDisplayText()) 
            {
                stringSize    = g.MeasureString(text, base.DataGridTableStyle.DataGrid.Font);
                if (stringSize.Width > widest) 
                {
                    widest = (int)Math.Ceiling(stringSize.Width);
                }
            }

            return new Size(widest + 25, combobox.PreferredHeight + 2);
        } // GetPreferredSize

        protected override void Paint(Graphics g, Rectangle bounds, CurrencyManager source, int rowNum) 
        {
            Paint(g, bounds, source, rowNum, false);
        } // Paint

        protected override void Paint(Graphics g, Rectangle bounds, CurrencyManager source, int rowNum, bool alignToRight) 
        {
            string            text                = GetColumnValueAtRow(source, rowNum).ToString();
            Brush                backBrush        = new SolidBrush(base.DataGridTableStyle.BackColor);
            Brush                foreBrush        = new SolidBrush(base.DataGridTableStyle.ForeColor);
            Rectangle        rect                = bounds;
            StringFormat    format            = new StringFormat();

            // Handle that the row can be selected.
            if (base.DataGridTableStyle.DataGrid.IsSelected(rowNum) == true) 
            {
                backBrush        = new SolidBrush(base.DataGridTableStyle.SelectionBackColor);
                foreBrush        = new SolidBrush(base.DataGridTableStyle.SelectionForeColor);
            }

            // Handle align to right.
            if (alignToRight == true) 
            {
                format.FormatFlags    = StringFormatFlags.DirectionRightToLeft;
            }

            // Handle alignment.
            switch (this.Alignment) 
            {
                case HorizontalAlignment.Left:
                    format.Alignment    = StringAlignment.Near;
                    break;
                case HorizontalAlignment.Right:
                    format.Alignment    = StringAlignment.Far;
                    break;
                case HorizontalAlignment.Center:
                    format.Alignment    = StringAlignment.Center;
                    break;
            }

            // Paint.
            format.FormatFlags        = StringFormatFlags.NoWrap;
            g.FillRectangle(backBrush, rect);
            rect.Offset(0, 2);
            rect.Height -= 2;
            g.DrawString(text, this.DataGridTableStyle.DataGrid.Font, foreBrush, rect, format);
            format.Dispose();
        } // PaintText

    } // DataGridLookupColumn
    #endregion

    DataGridComboBox#region DataGridComboBox
    //**********************************************************************************************
    //    DataGridComboBox
    //**********************************************************************************************
    public class DataGridComboBox : ComboBox 
    {
        private const int WM_KEYUP = 0x101;

        protected override void WndProc(ref System.Windows.Forms.Message message) 
        {
            // Ignore keyup to avoid problem with tabbing and dropdown list.
            if (message.Msg == WM_KEYUP) 
            {
                return;
            }

            base.WndProc(ref message);
        } // WndProc

        public string GetValueText(int index) 
        {
            // Validate the index.
            if ((index < 0) && (index >= base.Items.Count))
                throw new IndexOutOfRangeException("Invalid index.");

            // Get the text.
            string    text            = string.Empty;
            int        memIndex        = -1;
            try 
            {
                base.BeginUpdate();
                memIndex                    = base.SelectedIndex;
                base.SelectedIndex    = index;
                text                        = base.SelectedValue.ToString();
                base.SelectedIndex    = memIndex;
            } 
            catch 
            {
            } 
            finally 
            {
                base.EndUpdate();
            }

            return text;
        } // GetValueText

        public string GetDisplayText(int index) 
        {
            // Validate the index.
            if ((index < 0) && (index >= base.Items.Count))
                throw new IndexOutOfRangeException("Invalid index.");

            // Get the text.
            string    text            = string.Empty;
            int        memIndex        = -1;
            try 
            {
                base.BeginUpdate();
                memIndex                    = base.SelectedIndex;
                base.SelectedIndex    = index;
                text                        = base.SelectedItem.ToString();
                base.SelectedIndex    = memIndex;
            } 
            catch 
            {
            } 
            finally 
            {
                base.EndUpdate();
            }

            return text;
        } // GetDisplayText

        public string GetDisplayText(object value) 
        {    //mdified by zendyhu 2004-12  to fixed bug when the getValueByID
            string text1 = this.ValueMember;
            if (text1.Equals(string.Empty))
                return "";

            if (DataSource == null)
                return "";
            if (!(DataSource is IList))
            {
                return "";
            }

            foreach(object obj in (IList)DataSource)
            {
                object obj2 = FilterItemOnProperty(obj,text1);

                if(value.ToString().Trim().ToUpper() == obj2.ToString().Trim().ToUpper())
                {
                    return GetItemText(obj);
                }
            }
            return "";
            // Get the text.
//            string    text            = string.Empty;
//            int        memIndex        = -1;
//            try 
//            {                
//                base.BeginUpdate();
//                memIndex                    = base.SelectedIndex;
//                base.SelectedValue    = value;
//                text                        = base.Text.ToString();
//                base.SelectedIndex    = memIndex;
//            } 
//            catch 
//            {
//            } 
//            finally 
//            {
//                base.EndUpdate();
//            }
//
//            return text;
        } // GetDisplayText

        public string[] GetDisplayText() 
        {
            // Get the text.
            string[]    text            = new string[base.Items.Count];
            int        memIndex        = -1;
            try 
            {
                base.BeginUpdate();
                memIndex                    = base.SelectedIndex;
                for (int index = 0; index < base.Items.Count; index++) 
                {
                    base.SelectedIndex    = index;
                    text[index]                = base.SelectedItem.ToString();
                }
                base.SelectedIndex    = memIndex;
            } 
            catch 
            {
            } 
            finally 
            {
                base.EndUpdate();
            }

            return text;
        } // GetDisplayText

    } // DataGridComboBox
    #endregion

转载于:https://www.cnblogs.com/caomao/archive/2005/04/23/143939.html

在DataGrid中添加一个LookUpColumn,以比较灵活地实现DictValue值代替DictID值显示.相关推荐

  1. R语言编写自定义函数、评估回归模型预测变量的相对重要性(Relative importance)、通过在所有可能的子模型中添加一个预测变量而获得的R方的平均增加、评估预测变量的重要度、并通过点图可视化

    R语言编写自定义函数.评估回归模型预测变量的相对重要性(Relative importance).通过在所有可能的子模型中添加一个预测变量而获得的R方的平均增加.来评估预测变量的重要程度.并通过点图可 ...

  2. Visual Stdio 无法直接启动带有“类库输出类型”的项目若要调试此项目,请在此解决方案中添加一个引用库项目的可执行项目。将这个可执行项目设置为启动项目!

    Visual Stdio 无法直接启动带有"类库输出类型"的项目若要调试此项目,请在此解决方案中添加一个引用库项目的可执行项目.将这个可执行项目设置为启动项目! 参考文章: (1) ...

  3. python在子类中添加新的属性_pycharm实现在子类中添加一个父类没有的属性

    我就废话不多说了,还是直接看代码吧! class Car(): """一次模拟汽车的简单尝试""" def __init__(self, m ...

  4. php怎么添加会员卡,怎么在微信公众号中添加一个会员卡领取功能

    怎么在微信公众号中添加一个会员卡领取功能 发布时间:2020-12-09 16:06:27 来源:亿速云 阅读:129 作者:Leah 这篇文章将为大家详细讲解有关怎么在微信公众号中添加一个会员卡领取 ...

  5. 如何在RCP程序中添加一个banner栏

    前言:这段时间还算比较空闲,我准备把过去做过的有些形形色色,甚至有些奇怪的研究总结一下,也许刚好有人用的着也不一定,不枉为之抓耳挠腮的时光和浪费的电力.以前有个客户提出要在RCP程序中添加一个bann ...

  6. Entity Framework 的小实例:在项目中添加一个实体类,并做插入操作

    Entity Framework 的小实例:在项目中添加一个实体类,并做插入操作 Entity Framework 的小实例:在项目中添加一个实体类,并做插入操作 1>. 创建一个控制台程序 2 ...

  7. Frame中添加一个黄色的panel

    Frame中添加一个黄色的panel package p1;import java.awt.Color; import java.io.BufferedReader; import java.io.I ...

  8. 对类HelloWorld程序中添加一个MessageBox弹窗

    对类HelloWorld程序中添加一个MessageBox弹窗 分析: 任一程序运行的时候都会加载kernel32.dll的,但MessageBoxA()这个API却是在user32.dll中的.所以 ...

  9. 【Python3.7】就餐人数:在为完成练习 9-1 而编写的程序中,添加一个名为 number_served 的属性,并将其默认值设置为 0。根据这个类创建一个名为 restaurant 的实例

    # [Python3.7]就餐人数:在为完成练习 9-1 而编写的程序中,添加一个名为 number_served的属性,并将其默认值设置为 0.根据这个类创建一个名为 restaurant 的实例: ...

最新文章

  1. 市面上有没有靠谱的PM2.5检测仪?如何自己动手制作PM2.5检测仪
  2. 讲一点分布式的基础知识,图解!
  3. 一个通用Makefile详解
  4. 发送Gmail邀请.
  5. JS 开发常用工具函数
  6. import win32com.client在python中报错及其解决办法
  7. Atom飞行手册翻译: 3.6 图标
  8. 微信小程序接口测试时appid为空如何解决
  9. lisp 标注螺纹孔_螺纹的表示法和标注
  10. linux下的tuxedo开发实例
  11. 【干货】神经网络初始化trick:大神何凯明教你如何训练网络!
  12. XAP部署错误代码大全
  13. U盘越狱iPhone绕ID最新教程及各种坑解决,吐血之作(超详细超简单教程)
  14. python 源代码 macd双底 高 低_久其软件怎么样MACD指标的双底形态特征详解
  15. MPEG-DASH简介
  16. iOS开发——设置支持的iOS设备(512m内存以上设备)
  17. 山水盆景胶合时的留意问题
  18. LinkIn基于Dynamo设计的系统:伏地魔(voldemort)设计中文文档
  19. 使用IBM SPSS快速对数据进行分组
  20. 《Android App开发进阶与项目实战》出版后记

热门文章

  1. 为什么一定要读南瓜书?
  2. 隐藏十年竟无人发现!Sudo 漏洞被曝出:无需密码就能获取 root 权限
  3. 互联网人的平均时长,居然这么短...
  4. TOJ4537: n阶行列式
  5. libtool: line 454 CDPATH libtool: line 1132: func_opt_split: : command not found
  6. Centos7 下nginx nginx-1.13.4 安装
  7. 放弃java转战kotlin,我的心路历程
  8. word中使用MathType能做什么
  9. apache 和tomcat的区别
  10. 玩Android的第一天