如何在子节点树视图中添加复选框? [英] How to add checkbox in childnodes treeview?
本文介绍了如何在子节点树视图中添加复选框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用 c#
在 .NET 3.5
中使用 winforms
.现在我想在子节点中添加带有父节点和复选框的树视图...
I am working with winforms
in .NET 3.5
using c#
. now i want to add treeview with parent nodes and checkboxes in child nodes...
我已经通过以下代码完成了父节点的创建..
I have completed parent node creation by following code..
dt = conn.dataTable("select desgn from designation");
tvRoles.Nodes.Clear();
foreach (DataRow dr in dt.Rows)
{
TreeNode parent = new TreeNode();
parent.Text = dr[0].ToString();
string value = dr[0].ToString();
parent.Expand();
tvRoles.Nodes.Add(parent);
subLevel(parent, value);
}
现在我想在子节点中添加复选框..
Now I want to add checkboxes in child nodes..
你能帮助我吗?
推荐答案
如果你希望只有子节点有复选框,这里有一个解决方案:
If you want only children nodes have checkboxes, here is a solution:
//First, as I said, you have to set treeView.CheckBoxes = true;
//Second, set treeView.DrawMode = TreeViewDrawMode.OwnerDrawAll;
//Add this DrawNode event handler and enjoy =)
private void treeView_DrawNode(object sender, DrawTreeNodeEventArgs e)
{
if (e.Node.Parent == null)//If the Node is a Parent
{
int d = (int)(0.2*e.Bounds.Height);
Rectangle rect = new Rectangle(d + treeView.Margin.Left, d + e.Bounds.Top, e.Bounds.Height - d*2, e.Bounds.Height - d*2);
e.Graphics.FillRectangle(new SolidBrush(Color.FromKnownColor(KnownColor.Control)), rect);
e.Graphics.DrawRectangle(Pens.Silver, rect);
StringFormat sf = new StringFormat() { LineAlignment = StringAlignment.Center, Alignment = StringAlignment.Center };
e.Graphics.DrawString(e.Node.IsExpanded ? "-" : "+", treeView.Font, new SolidBrush(Color.Blue), rect, sf);
//Draw the dotted line connecting the expanding/collapsing button and the node Text
using (Pen dotted = new Pen(Color.Black) {DashStyle = System.Drawing.Drawing2D.DashStyle.Dot})
{
e.Graphics.DrawLine(dotted, new Point(rect.Right + 1, rect.Top + rect.Height / 2), new Point(rect.Right + 4, rect.Top + rect.Height / 2));
}
//Draw text
sf.Alignment = StringAlignment.Near;
Rectangle textRect = new Rectangle(e.Bounds.Left + rect.Right + 4, e.Bounds.Top, e.Bounds.Width - rect.Right - 4, e.Bounds.Height);
if (e.Node.IsSelected)
{
SizeF textSize = e.Graphics.MeasureString(e.Node.Text, treeView.Font);
e.Graphics.FillRectangle(new SolidBrush(SystemColors.Highlight), new RectangleF(textRect.Left, textRect.Top, textSize.Width, textRect.Height));
}
e.Graphics.DrawString(e.Node.Text, treeView.Font, new SolidBrush(treeView.ForeColor), textRect,sf);
}
else e.DrawDefault = true;
}
为了使它更好,您可能想要创建自己的 TreeView
,覆盖 OnDrawNode
(使用与我上面发布的相同的代码)并设置 DoubleBuffered=在构造函数中为 true
.
To make it better, you may want to create your own TreeView
, override OnDrawNode
(with the same code as I posted above) and set DoubleBuffered=true
in the constructor.
这篇关于如何在子节点树视图中添加复选框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文