qhnokia

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
#region 示例 1 -- 拥有多列的组合框

// 初始化DataTable:
//
// 创建一个名为dtTest的数据表,为其添加2列
// ID: int
// Name: string
//
DataTable dtTest = new DataTable();
dtTest.Columns.Add(
"ID", typeof(int));
dtTest.Columns.Add(
"Name", typeof(string));

dtTest.Rows.Add(
1, "John");
dtTest.Rows.Add(
2, "Amy");
dtTest.Rows.Add(
3, "Tony");
dtTest.Rows.Add(
4, "Bruce");
dtTest.Rows.Add(
5, "Allen");

// 将组合框的数据源设置为DataTable。
this.comboBox1.DataSource = dtTest;
this.comboBox1.DisplayMember = "Name";
this.comboBox1.ValueMember = "ID";

// 将组合框的 DrawMode 设置为OwnerDrawFixed。
this.comboBox1.DrawMode = DrawMode.OwnerDrawFixed;

// 在DrawItem事件中绘制子项。
this.comboBox1.DrawItem += delegate(object cmb, DrawItemEventArgs args)
{
// 绘制默认的背景
args.DrawBackground();

// 因为组合框被绑定到DataTable,所以组合框的子项是DataRowView对象。
DataRowView drv = (DataRowView)this.comboBox1.Items[args.Index];

// 取出每一列的值。
string id = drv["id"].ToString();
string name = drv["name"].ToString();

// 获得第一列的边界。
Rectangle r1 = args.Bounds;
r1.Width
/= 2;

// 绘制第一列的文本。
using (SolidBrush sb = new SolidBrush(args.ForeColor))
{
args.Graphics.DrawString(id, args.Font, sb, r1);
}

// 绘制一条分割线分割不同的列。
using (Pen p = new Pen(Color.Black))
{
args.Graphics.DrawLine(p, r1.Right,
0, r1.Right, r1.Bottom);
}

// 获取第二列的边界。
Rectangle r2 = args.Bounds;
r2.X
= args.Bounds.Width/2;
r2.Width
/= 2;

// 绘制第二列的文本。
using (SolidBrush sb = new SolidBrush(args.ForeColor))
{
args.Graphics.DrawString(name, args.Font, sb, r2);
}
};

#endregion

 

posted on 2010-11-23 15:20  其乐无穷  阅读(424)  评论(0编辑  收藏  举报