日期:2014-05-18 浏览次数:20879 次
private void button2_Click(object sender, EventArgs e) { if (txtDeptName.Text == "") { MessageBox.Show("请输入要添加的部门名称。"); return; } if (checkBox1.Checked) { foreach (TreeNode childnode in treeView1.SelectedNode.Nodes) { if (childnode.Text == txtDeptName.Text) { MessageBox.Show("此部门已经存在。"); return; } } treeView1.SelectedNode.Nodes.Add(txtDeptName.Text); treeView1.SelectedNode.Expand(); } else { foreach (TreeNode node in treeView1.Nodes) { if (node.Text == txtDeptName.Text) { MessageBox.Show("此部门已经存在。"); return; } } treeView1.Nodes.Add(txtDeptName.Text); } }
private void AddNode(TreeNodeCollection treeNodes, String value) { foreach (TreeNode childnode in treeNodes) { if (childnode.Text == value) { MessageBox.Show("此部门已经存在。"); return; } } treeNodes.Add(txtDeptName.Text); } private void button1_Click(object sender, EventArgs e) { if (txtDeptName.Text == "") { MessageBox.Show("请输入要添加的部门名称。"); return; } if (checkBox1.Checked) { if (treeView1.SelectedNode != null) { AddNode(treeView1.SelectedNode.Nodes, txtDeptName.Text); } } else { AddNode(treeView1.Nodes, txtDeptName.Text); } }
------解决方案--------------------
private void button2_Click(object sender, EventArgs e) { if (txtDeptName.Text == "") { MessageBox.Show("请输入要添加的部门名称。"); return; } var nodes = checkBox1.Checked ? treeView1.SelectedNode.Nodes : treeView1.Nodes; bool exit = nodes.Cast<TreeNode>().Any(v1 => v1.Text != txtDeptName.Text); if (!exit) { MessageBox.Show("此部门已经存在。"); return; } nodes.Add(txtDeptName.Text); if (checkBox1.Checked) { treeView1.SelectedNode.Expand(); } }