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

 在一个项目中,我遇到这样一个问题: 数据库字段只存储了一个字典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值.具体代码如下:

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



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

ExpandedBlockStart.gif ContractedBlock.gif /**/ /*本代码原稿由http://www.codeproject.com/cs/miscctrl/RenDataGridComboBoxColumn.asp获取,并做了相应的改动 by Zendyhu
ExpandedBlockEnd.gif
*/

ExpandedBlockStart.gifContractedBlock.gif
DataGridLookupColumn #region DataGridLookupColumn
InBlock.gif    
//**********************************************************************************************
InBlock.gif    
//    DataGridLookupColumn
InBlock.gif    
//**********************************************************************************************
InBlock.gif
    public class DataGridLookupColumn : DataGridColumnStyle 
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif//DataGridLookupColumn {
InBlock.gif
        private    DataGridComboBox    combobox;
InBlock.gif        
private    bool                    edit;
InBlock.gif
InBlock.gif        
//-------------------------------------------------------------------------------------------
InBlock.gif        
//    Constructors and destructors
InBlock.gif        
//-------------------------------------------------------------------------------------------
InBlock.gif
        public DataGridLookupColumn() 
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            combobox                                        
= new DataGridComboBox();
InBlock.gif            combobox.Visible                            
= false;
InBlock.gif            combobox.DropDownStyle                    
= ComboBoxStyle.DropDownList;
InBlock.gif            combobox.Leave                                
+= new EventHandler(ComboHide);
InBlock.gif            combobox.SelectionChangeCommitted    
+= new EventHandler(ComboStartEditing);
InBlock.gif            edit                                            
= false;
ExpandedSubBlockEnd.gif        }
 // DataGridLookupColumn
InBlock.gif
InBlock.gif        
//-------------------------------------------------------------------------------------------
InBlock.gif        
//    Properties
InBlock.gif        
//-------------------------------------------------------------------------------------------
InBlock.gif
        public ComboBox comboBox 
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
get 
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
return combobox;
ExpandedSubBlockEnd.gif            }

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

InBlock.gif        
private void ComboStartEditing(object sender, EventArgs e) 
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
// Enter edit mode.
InBlock.gif
            edit = true;
InBlock.gif            
base.ColumnStartedEditing((Control)sender);
ExpandedSubBlockEnd.gif        }
 // ComboStartEditing
InBlock.gif
InBlock.gif        
//-------------------------------------------------------------------------------------------
InBlock.gif        
//    Override DataGridColumnStyle
InBlock.gif        
//-------------------------------------------------------------------------------------------
InBlock.gif
        protected override void SetDataGridInColumn(DataGrid value) 
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
// Add the ComboBox to the DataGrids controls collection.
InBlock.gif            
// This ensures correct DataGrid scrolling.
InBlock.gif
            value.Controls.Add(combobox);
InBlock.gif            
base.SetDataGridInColumn(value);
ExpandedSubBlockEnd.gif        }
 // SetDataGridInColumn
InBlock.gif

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

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

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

InBlock.gif
InBlock.gif            
return true;
ExpandedSubBlockEnd.gif        }
 // Commit
InBlock.gif

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

InBlock.gif        
protected override void SetColumnValueAtRow(CurrencyManager source, int rowNum, object value) 
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
// Save the data (value) to the DataGrid datasource.
InBlock.gif            
// I try a few different types, because I often uses GUIDs as keys in my
InBlock.gif            
// data.
InBlock.gif
InBlock.gif            
// String.
InBlock.gif
            try 
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
base.SetColumnValueAtRow(source, rowNum, value.ToString());
InBlock.gif                
return;
ExpandedSubBlockEnd.gif            }
 
ExpandedSubBlockStart.gifContractedSubBlock.gif            
catch dot.gif{}
InBlock.gif
InBlock.gif            
// Guid.
InBlock.gif
            try 
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
base.SetColumnValueAtRow(source, rowNum, new Guid(value.ToString()));
InBlock.gif                
return;
ExpandedSubBlockEnd.gif            }
 
ExpandedSubBlockStart.gifContractedSubBlock.gif            
catch dot.gif{}
InBlock.gif
InBlock.gif            
// Object (default).
InBlock.gif
            base.SetColumnValueAtRow(source, rowNum, value);
ExpandedSubBlockEnd.gif        }
 // SetColumnValueAtRow
InBlock.gif

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

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

ExpandedSubBlockEnd.gif            }

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

InBlock.gif        
protected override void Paint(Graphics g, Rectangle bounds, CurrencyManager source, int rowNum) 
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            Paint(g, bounds, source, rowNum, 
false);
ExpandedSubBlockEnd.gif        }
 // Paint
InBlock.gif

InBlock.gif        
protected override void Paint(Graphics g, Rectangle bounds, CurrencyManager source, int rowNum, bool alignToRight) 
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
string            text                = GetColumnValueAtRow(source, rowNum).ToString();
InBlock.gif            Brush                backBrush        
= new SolidBrush(base.DataGridTableStyle.BackColor);
InBlock.gif            Brush                foreBrush        
= new SolidBrush(base.DataGridTableStyle.ForeColor);
InBlock.gif            Rectangle        rect                
= bounds;
InBlock.gif            StringFormat    format            
= new StringFormat();
InBlock.gif
InBlock.gif            
// Handle that the row can be selected.
InBlock.gif
            if (base.DataGridTableStyle.DataGrid.IsSelected(rowNum) == true
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                backBrush        
= new SolidBrush(base.DataGridTableStyle.SelectionBackColor);
InBlock.gif                foreBrush        
= new SolidBrush(base.DataGridTableStyle.SelectionForeColor);
ExpandedSubBlockEnd.gif            }

InBlock.gif
InBlock.gif            
// Handle align to right.
InBlock.gif
            if (alignToRight == true
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                format.FormatFlags    
= StringFormatFlags.DirectionRightToLeft;
ExpandedSubBlockEnd.gif            }

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

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

ExpandedSubBlockEnd.gif    }
 // DataGridLookupColumn
ExpandedBlockEnd.gif
    #endregion

None.gif
ExpandedBlockStart.gifContractedBlock.gif    
DataGridComboBox #region DataGridComboBox
InBlock.gif    
//**********************************************************************************************
InBlock.gif    
//    DataGridComboBox
InBlock.gif    
//**********************************************************************************************
InBlock.gif
    public class DataGridComboBox : ComboBox 
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
private const int WM_KEYUP = 0x101;
InBlock.gif
InBlock.gif        
protected override void WndProc(ref System.Windows.Forms.Message message) 
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
// Ignore keyup to avoid problem with tabbing and dropdown list.
InBlock.gif
            if (message.Msg == WM_KEYUP) 
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
return;
ExpandedSubBlockEnd.gif            }

InBlock.gif
InBlock.gif            
base.WndProc(ref message);
ExpandedSubBlockEnd.gif        }
 // WndProc
InBlock.gif

InBlock.gif        
public string GetValueText(int index) 
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
// Validate the index.
InBlock.gif
            if ((index < 0&& (index >= base.Items.Count))
InBlock.gif                
throw new IndexOutOfRangeException("Invalid index.");
InBlock.gif
InBlock.gif            
// Get the text.
InBlock.gif
            string    text            = string.Empty;
InBlock.gif            
int        memIndex        = -1;
InBlock.gif            
try 
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
base.BeginUpdate();
InBlock.gif                memIndex                    
= base.SelectedIndex;
InBlock.gif                
base.SelectedIndex    = index;
InBlock.gif                text                        
= base.SelectedValue.ToString();
InBlock.gif                
base.SelectedIndex    = memIndex;
ExpandedSubBlockEnd.gif            }
 
InBlock.gif            
catch 
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
ExpandedSubBlockEnd.gif            }
 
InBlock.gif            
finally 
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
base.EndUpdate();
ExpandedSubBlockEnd.gif            }

InBlock.gif
InBlock.gif            
return text;
ExpandedSubBlockEnd.gif        }
 // GetValueText
InBlock.gif

InBlock.gif        
public string GetDisplayText(int index) 
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
// Validate the index.
InBlock.gif
            if ((index < 0&& (index >= base.Items.Count))
InBlock.gif                
throw new IndexOutOfRangeException("Invalid index.");
InBlock.gif
InBlock.gif            
// Get the text.
InBlock.gif
            string    text            = string.Empty;
InBlock.gif            
int        memIndex        = -1;
InBlock.gif            
try 
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
base.BeginUpdate();
InBlock.gif                memIndex                    
= base.SelectedIndex;
InBlock.gif                
base.SelectedIndex    = index;
InBlock.gif                text                        
= base.SelectedItem.ToString();
InBlock.gif                
base.SelectedIndex    = memIndex;
ExpandedSubBlockEnd.gif            }
 
InBlock.gif            
catch 
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
ExpandedSubBlockEnd.gif            }
 
InBlock.gif            
finally 
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
base.EndUpdate();
ExpandedSubBlockEnd.gif            }

InBlock.gif
InBlock.gif            
return text;
ExpandedSubBlockEnd.gif        }
 // GetDisplayText
InBlock.gif

InBlock.gif        
public string GetDisplayText(object value) 
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{    //mdified by zendyhu 2004-12  to fixed bug when the getValueByID
InBlock.gif
            string text1 = this.ValueMember;
InBlock.gif            
if (text1.Equals(string.Empty))
InBlock.gif                
return "";
InBlock.gif
InBlock.gif            
if (DataSource == null)
InBlock.gif                
return "";
InBlock.gif            
if (!(DataSource is IList))
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
return "";
ExpandedSubBlockEnd.gif            }

InBlock.gif
InBlock.gif            
foreach(object obj in (IList)DataSource)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
object obj2 = FilterItemOnProperty(obj,text1);
InBlock.gif
InBlock.gif                
if(value.ToString().Trim().ToUpper() == obj2.ToString().Trim().ToUpper())
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    
return GetItemText(obj);
ExpandedSubBlockEnd.gif                }

ExpandedSubBlockEnd.gif            }

InBlock.gif            
return "";
InBlock.gif            
// Get the text.
InBlock.gif
//            string    text            = string.Empty;
InBlock.gif
//            int        memIndex        = -1;
InBlock.gif
//            try 
InBlock.gif
//            {                
InBlock.gif
//                base.BeginUpdate();
InBlock.gif
//                memIndex                    = base.SelectedIndex;
InBlock.gif
//                base.SelectedValue    = value;
InBlock.gif
//                text                        = base.Text.ToString();
InBlock.gif
//                base.SelectedIndex    = memIndex;
InBlock.gif
//            } 
InBlock.gif
//            catch 
InBlock.gif
//            {
InBlock.gif
//            } 
InBlock.gif
//            finally 
InBlock.gif
//            {
InBlock.gif
//                base.EndUpdate();
InBlock.gif
//            }
InBlock.gif
//
InBlock.gif
//            return text;
ExpandedSubBlockEnd.gif
        }
 // GetDisplayText
InBlock.gif

InBlock.gif        
public string[] GetDisplayText() 
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
// Get the text.
InBlock.gif
            string[]    text            = new string[base.Items.Count];
InBlock.gif            
int        memIndex        = -1;
InBlock.gif            
try 
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
base.BeginUpdate();
InBlock.gif                memIndex                    
= base.SelectedIndex;
InBlock.gif                
for (int index = 0; index < base.Items.Count; index++
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    
base.SelectedIndex    = index;
InBlock.gif                    text[index]                
= base.SelectedItem.ToString();
ExpandedSubBlockEnd.gif                }

InBlock.gif                
base.SelectedIndex    = memIndex;
ExpandedSubBlockEnd.gif            }
 
InBlock.gif            
catch 
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
ExpandedSubBlockEnd.gif            }
 
InBlock.gif            
finally 
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
base.EndUpdate();
ExpandedSubBlockEnd.gif            }

InBlock.gif
InBlock.gif            
return text;
ExpandedSubBlockEnd.gif        }
 // GetDisplayText
InBlock.gif

ExpandedSubBlockEnd.gif    }
 // DataGridComboBox
ExpandedBlockEnd.gif
    #endregion



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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值