【发布时间】:2011-05-06 18:26:15
【问题描述】:
我正在编写一个应用程序,在其中使用数据库的模式填写 TreeView。我通过遍历每个表名并输入 GetSchema 来做到这一点。然后,根据 DataType 和名称,我选择要添加新项目的父节点。有时该项目在树节点中不存在(取决于用户设置,某些表可能已添加为树视图的节点,也可能未添加),这很好,在这种情况下我想要:
A) 要抛出异常,所以我知道它未能按要求找到节点。或者 B) 为失败的访问者返回 null。
我的代码的一个(高度修改的)sn-p:
TreeNode parent = null;
if( tableName.StartsWith("prefix") )
{
parent = tablesNode.Nodes["Node Name which might not exist"];
}
if (parent == null && IgnorePrefixedTables)
{
continue;
}
else if (parent == null)
{
throw Exception();
}
....<More Code For Filling Out that node>...
问题是,当我单步执行此代码(或者更确切地说,真正的代码)时,当我到达不存在的节点名称的 tablesNode.Nodes["Node Name which may not exist"] 时,我无法捕获异常,因为没有抛出任何异常。如果我踏入或越过那行代码,整个方法会将我返回到最高级别(我的表单立即显示并且 UI 部分完成)。这是怎么回事?
[编辑]
这是我的问题的一个非常简化的版本:
namespace TestZone
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
treeView1.Nodes.Add("Hello", "Hello");
var x = treeView1.Nodes["Hello"];
x.Nodes.Add("World-PL", "Swiat");
x.Nodes.Add("World-EN", "World");
var y = treeView1.Nodes["World-EN"];
MessageBox.Show(y.Text);
y = treeView1.Nodes["World-SP"];
MessageBox.Show(y.Text);
y = treeView1.Nodes["World-PL"];
MessageBox.Show(y.Text);
}
}
}
代码依赖于 Form1 上的 textBox1。 (PS PL 是波兰语)。显然,treeView1 也找不到 World-EN,这让我觉得我 真的 不了解 treeView 的工作原理。第一个 MessageBox 永远不会显示和断点 y = treeView1.Nodes["World-SP"];失败(因为那行代码永远不会被调用)。
【问题讨论】: