向treeview C#添加项目时出错

时间:2013-08-19 08:54:42

标签: c# wpf treeview sql-server-ce

我编写了以下代码来创建树视图: 它从sqlCEserver读取数据并生成视图。在我进入内部while循环以在标题中添加子项之前,它工作正常。

private void ClientTree_Initialized(object sender, EventArgs e)
       {
            string moduleCat = null;
            string Cname = null;
            SqlCeConnection _con = new SqlCeConnection(@"Data Source=C:\Users\Family\Desktop\Tranchulas projects\ControlCenter\ControlCenter\bin\Debug\ClientDB.sdf");
            _con.Open();
            SqlCeDataReader _reader = null;
            SqlCeDataReader _reader1 = null;
            SqlCeCommand readMod = new SqlCeCommand(@"SELECT DISTINCT ModuleID FROM ClientRecord", _con);

            _reader = readMod.ExecuteReader();
            while(_reader.Read())
            {

                moduleCat = _reader["ModuleID"].ToString();

                treeItem = new TreeViewItem();
                treeItem.Header = moduleCat;

                SqlCeCommand readName = new SqlCeCommand(@"SELECT Cname FROM ClientRecord WHERE (ModuleID = '" + moduleCat + @"')", _con);
                _reader1 = readName.ExecuteReader();
                while (_reader1.Read())
                {
                    Cname = _reader["Cname"].ToString();
                    treeItem.Items.Add(new TreeViewItem() { Header = Cname });
                    ClientTree.Items.Add(treeItem);
                }
            }
        }

它给出了这个例外:

System.Windows.Markup.XamlParseException occurred
  HResult=-2146233087
  Message='Initialization of 'System.Windows.Controls.TreeView' threw an exception.' Line number '10' and line position '99'.
  Source=PresentationFramework
  LineNumber=10
  LinePosition=99

第10行是:

<TreeView x:Name="ClientTree" Height="350.4" Width="164.2" HorizontalAlignment="Left" VerticalAlignment="Top" Initialized="ClientTree_Initialized" />

1 个答案:

答案 0 :(得分:0)

如果在注释掉内部while循环时问题消失了,那么它在xaml中就不是问题了。 (因为没有任何改变)对吧?但是,您的异常表明它是一个xamlParseException,很奇怪。

你可以做的最好的事情是将一行InitializeComponent()放在try-catch语句中,并在catchblock中设置一个断点。现在,您可以访问完整的堆栈跟踪,并获得所需的alInrerexception信息! 祝好运。

InitializeComponent位于代码隐藏的构造函数中。

try
{
  InitializeComponent();
}
catch ( Exception ex )
{
  // set breakpoint here, and watch StackTrace
}