当我使用treeview控件的MouseClick事件时,总是选择树中的第一个节点.如何使用户选择当前节点?我正在使用C#.
这是我当前正在使用的代码:
private void TVRecorder_MouseClick(object sender, MouseEventArgs e)
{
TreeNode selectedNode = TVRecorder.HitTest(e.Location).Node;
if (selectedNode != null)
{
if (selectedNode.SelectedImageKey == "Test_Space")
{
frmRepository rep = new frmRepository();
string ssql = string.Empty;
rep.label1.Text = "Scenario-RepositoryDetails";
rep.LoadAppSettings();
SqlConnection con4 = new SqlConnection();
con4.ConnectionString = "Data Source=" + rep.ScnServer + ";" + "initial catalog=" + rep.ScnDbName + ";" + "User Id=" + rep.ScnUserName + ";" + "Password=" + rep.ScnPwd;
try
{
con4.Open();
}
catch
{
MessageBox.Show("Connection Failed");
}
ssql = "scn_select_testplan_sp";
SqlCommand cmd = new SqlCommand(ssql, con4);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@testspace_key", SqlDbType.Int);
cmd.Parameters["@testspace_key"].Value = testspace_key;
SqlDataReader _datareader = cmd.ExecuteReader();
try
{
while (_datareader.Read())
{
testplan_key = (int)_datareader["testplan_key"];
testplan_desc = (string)_datareader["testplan_desc"];
//selectedNode.Nodes[0].Nodes.Add(Convert.ToString(testplan_key), testplan_desc, "P", "Test_Plan");
TVRecorder.Nodes[0].Nodes.Add(Convert.ToString(testplan_key), testplan_desc, "P", "Test_Plan");
TVRecorder.Visible = true;
TVRecorder.HideSelection = false;
}
}
catch (Exception ex)
{
throw ex;
}
}
提前致谢…
解决方法:
您可以将TreeView控件公开的HitTest
method与发生MouseClick事件时的鼠标指针位置结合使用(e.Location
),以确定单击了哪个节点(因此将在事件结束时显示为选中状态).例如:
private void TreeView_MouseClick(object sender, MouseEventArgs e)
{
// Get the node that was clicked
TreeNode selectedNode = myTreeView.HitTest(e.Location).Node;
if (selectedNode != null)
{
// ...
// Do something with the selected node here...
}
}
请注意,上面的代码在执行其他操作之前先进行检查,以确保selectedNode不为null.如果用户单击了不是节点的对象,则HitTest方法检索的selectedNode对象将为null.
现在可能对您不起作用,因为您尝试使用TreeView控件的SelectedNode
property.运行MouseClick事件处理程序方法中的代码时,尚未选择该节点-仅在执行该代码后才选择该节点.相反,使用上述方法将使您能够到达最终将被更直接选择的节点.
编辑以下有关您的更新和评论的内容:
在我看来,这很简单.此代码行中出现问题:
TVRecorder.Nodes[0].Nodes.Add(Convert.ToString(testplan_key), testplan_desc, "P", "Test_Plan");
上面的代码将新节点添加为出现在TreeView中的第一个节点的子节点.相反,在我看来,您希望将它们添加为所选节点的子级.您已经确定了所选节点是什么(请参见答案的上面部分),因此只需修改代码即可将新节点添加为所选节点的子节点,如下所示:
selectedNode.Nodes.Add(Convert.ToString(testplan_key), testplan_desc, "P", "Test_Plan");
请记住,每个节点(TreeNode
class的一个实例)都有一个Nodes
property,它公开了TreeNodeCollection
.此集合包含该节点的所有子节点. MSDN可能比我更好地解释了这一点:
The
Nodes
property can hold a
collection of otherTreeNode
objects.
Each of the tree node[s] in the
collection has aNodes
property that
can contain its ownTreeNodeCollection
. This nesting of
tree nodes can make it difficult to
navigate a tree structure. TheFullPath
property makes it easier to
determine your location in a tree.