Winform Combobox+Tooltip 扩展tips功能
2011-07-02 19:50 假面Wilson 阅读(1712) 评论(0) 编辑 收藏 举报 创建Windows服务
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Threading;
namespace QouShui.DLL.ComboBoxs
{
/// <summary>
/// 支持显示提示框的combobox
/// 在displayMember和valueMember外,增加一个tipMember,用于显示提示内容,理论上还可以增加多个tipMember
/// </summary>
public partial class ComboBoxWithToolTipAndDataSource : ComboBox
{
public ComboBoxWithToolTipAndDataSource()
{
InitializeComponent();
this.DropDown += new EventHandler(ComboBoxWithToolTipAndDataSource_DropDown);
this.DropDownClosed += new EventHandler(ComboBoxWithToolTipAndDataSource_DropDownClosed);
this.DrawItem += new DrawItemEventHandler(ComboBoxWithToolTipAndDataSource_DrawItem);
}
private string tipMember="";
/// <summary>用于显示提示说明的列
/// </summary>
[System.ComponentModel.Description("用于显示提示说明的列")]
public string TipMember
{
get
{
return tipMember;
}
set
{
tipMember = value;
}
}
private void ComboBoxWithToolTipAndDataSource_DrawItem(object sender, DrawItemEventArgs e)
{
try
{
e.DrawBackground();
DataTable dt = DataSource as DataTable;
if (dt != null)
{
if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
{
e.Graphics.DrawString(dt.Rows[e.Index][DisplayMember].ToString(), e.Font, SystemBrushes.HighlightText, e.Bounds);
if (tipMember.Length > 0)
{
tp.Show(dt.Rows[e.Index][TipMember].ToString(), this, e.Bounds.Width, e.Bounds.Y + Height);
}
}
else
{
e.Graphics.DrawString(dt.Rows[e.Index][DisplayMember].ToString(), e.Font, SystemBrushes.WindowText, e.Bounds);
}
}
else
{
DataView dv = DataSource as DataView;
if (dv == null)
return;
if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
{
e.Graphics.DrawString(dv[e.Index][DisplayMember].ToString(), e.Font, SystemBrushes.HighlightText, e.Bounds);
if (tipMember.Length > 0)
tp.Show(dv[e.Index][tipMember].ToString(), this, e.Bounds.Width, e.Bounds.Y + Height);
}
else
{
e.Graphics.DrawString(dv[e.Index][DisplayMember].ToString(), e.Font, new SolidBrush(e.ForeColor), e.Bounds);
}
}
e.DrawFocusRectangle();
}
catch
{
}
}
void ComboBoxWithToolTipAndDataSource_DropDownClosed(object sender, EventArgs e)
{
tp.Active = false ;
}
void ComboBoxWithToolTipAndDataSource_DropDown(object sender, EventArgs e)
{
tp.Active = true ;
}
}
}
前台调用
LoadData()
{
DataTable dt = new DataTable();
dt.Columns.Add("名称");
dt.Columns.Add("编号",typeof(int));
dt.Columns.Add("说明");
dt.Rows.Add(new object[] { "清明节", 0, "4月3日,三天" });
dt.Rows.Add(new object[] { "劳动节", 1, "5月1日,七天" });
dt.Rows.Add(new object[] { "国庆节", 2, "10月1日,8天" });
comboBoxWithToolTipAndDataSource1.DataSource = dt;
comboBoxWithToolTipAndDataSource1.DisplayMember = "名称";
comboBoxWithToolTipAndDataSource1.ValueMember = "编号";
comboBoxWithToolTipAndDataSource1.TipMember = "说明";
comboBoxWithToolTipAndDataSource1.DropDownStyle = ComboBoxStyle.DropDownList;
}