本文介绍了向treeview C#添加项目时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我编写了以下代码来创建树视图:它从sqlCEserver读取数据并生成视图。它在我进入内部while循环之前正常工作以在标题中添加子项。I have written the following code to create a tree view: it reads data from a sqlCEserver and generates view according. It was working fine before i entered the inner while loop to add sub items in header.private void ClientTree_Initialized(object sender, EventArgs e) { string moduleCat = null; string Cname = null; SqlCeConnection _con = new SqlCeConnection(@"Data Source=C:\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); } } } 它给出了这个例外:it gave this exception: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行是: b $ bline number 10 is:<TreeView x:Name="ClientTree" Height="350.4" Width="164.2" HorizontalAlignment="Left" VerticalAlignment="Top" Initialized="ClientTree_Initialized" />推荐答案我认为问题在于你的第二个while循环中的代码。请注意,您正在_reader中查找Cname字段,该字段不在此阅读器中...I think the issue is with the code in your second while loop. Notice that you are looking in the _reader for the 'Cname' field which isn't in this reader...while (_reader1.Read()){ Cname = _reader["Cname"].ToString(); treeItem.Items.Add(new TreeViewItem() { Header = Cname }); ClientTree.Items.Add(treeItem);} ...我很确定你想要在你的第二个while循环中调用第二个阅读器(_reader1)。像这样......I am pretty sure you want to call the second reader (_reader1) in your second while loop. Like so...while (_reader1.Read()){ Cname = _reader1["Cname"].ToString(); treeItem.Items.Add(new TreeViewItem() { Header = Cname }); ClientTree.Items.Add(treeItem);} 这篇关于向treeview C#添加项目时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 08-18 20:48