防止用户更改TreeView中的复选框 [英] Prevent user from altering Check boxes in TreeView
问题描述
我有一个winforms树形视图,其中添加了节点,并根据数据库值以编程方式检查状态设置.我试图防止用户更改检查状态并遇到麻烦.我不确定要触发哪个事件以保持检查状态不变.
I have a winforms treeview with nodes added and check state set programmatically based on the database values. I am trying to prevent users from altering the check status and am having trouble. I am not sure what event to fire to keep the check state unaltered.
下面是我的代码:
private void BuildRolesTree(int ParentID, TreeNode pNode, DataSet SourceDS)
{
DataView dvwData = new DataView(SourceDS.Tables[0]);
dvwData.RowFilter = "[parent_id] = " + ParentID;
if (this.InvokeRequired)
{
BuildReportTreeDelegate d = new BuildReportTreeDelegate(BuildRolesTree);
this.Invoke(d, new object[] { ParentID, pNode, SourceDS });
}
else
{
foreach (DataRowView Row in dvwData)
{
TreeNode zNode;
if (pNode == null)
zNode = tv_Permissions.Nodes.Add(Row["node_id"].ToString(), Row["display_access_description"].ToString().Trim());
else zNode = pNode.Nodes.Add(Row["node_id"].ToString(), Row["display_access_description"].ToString().Trim());
if (Convert.ToInt32(Row["is_selected"]) == 1)
zNode.Checked = true;
else if (Convert.ToInt32(Row["is_selected"]) == 0)
zNode.Checked = false;
BuildRolesTree(Convert.ToInt32(Row["node_id"].ToString()), zNode, SourceDS);
}
}
}
private void PermissionsNode_AfterCheck(object sender, TreeViewEventArgs e)
{
if(e.Action != TreeViewAction.Unknown)
{
if(e.Node.Checked) //leave it checked
e.Node.Checked = e.Node.Checked????
//I am looking for something like the below
//e.Checked.NewValue = e.Checked.CurrentValue;
}
}
}
感谢您的帮助.
}
ANy help is appreciated.
推荐答案
You can handle BeforeCheck and set e.Cancel = true
to prevent changing the check:
private void treeView1_BeforeCheck(object sender, TreeViewCancelEventArgs e)
{
e.Cancel = true;
}
但是,当双击CheckBoxes时,TreeView中有一个问题,检查事件无法按预期进行.遵循我在链接的帖子中分享的解决方案,或使用以下具有 CheckBoxEdit
属性(类似于 LabelEdit
)的 ExTreeView
您启用或禁用CheckBoxes上的检查:
However, there is a problem in TreeView when double click on CheckBoxes the check events not work as expected. Follow the solution that I've shared in the linked post or use the following ExTreeView
which has a CheckBoxEdit
property (similar to LabelEdit
) which allows you enable or disable checking on CheckBoxes:
public class ExTreeView : TreeView
{
private const int WM_LBUTTONDBLCLK = 0x0203;
protected override void WndProc(ref Message m)
{
if (m.Msg == WM_LBUTTONDBLCLK)
{
var info = this.HitTest(PointToClient(Cursor.Position));
if (info.Location == TreeViewHitTestLocations.StateImage)
{
m.Result = IntPtr.Zero;
return;
}
}
base.WndProc(ref m);
}
[DefaultValue(true)]
public bool CheckBoxEdit { get; set; } = true;
protected override void OnBeforeCheck(TreeViewCancelEventArgs e)
{
base.OnBeforeCheck(e);
e.Cancel = !CheckBoxEdit;
}
}
这篇关于防止用户更改TreeView中的复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!