I am new to using tree views, and I want to make sure that there can only be one child node in the tree view, and if someone tries to check more than one, it stops the validation event and deselects all the parent and child nodes. How can I do it? So far this is what I have, but it's freaky. Any suggestions?
Update: To clarify some things, this is a treeview of the win form, and the parent node is a category, and each category can contain multiple elements. I just want the user to be able to select one category and one item from the category at a time.
private void tvRecipes_BeforeCheck(object sender, TreeViewCancelEventArgs e)
{
int checkedNodeCount = 0;
if (e.Node.Parent != null && !e.Node.Parent.Checked)
e.Cancel = true;
else
{
foreach (TreeNode node in tvRecipes.Nodes)
{
if (node.Checked)
++checkedNodeCount;
if (checkedNodeCount > 2)
{
MessageBox.Show("Only one recipe can be selected at a time, please deselect the current recipe and try again.", "Too Many Recipes Selected", MessageBoxButtons.OK, MessageBoxIcon.Error);
e.Cancel = true;
}
}
}
After some confusion, I realized what solution I got. I posted it below:
private bool CheckNumOfSelectedChildern(TreeViewEventArgs e)
{
bool Valid = true;
int selectedChildern = 0;
foreach (TreeNode node in tvRecipes.Nodes)
{
if (node.Checked)
{
foreach (TreeNode child in node.Nodes)
{
if (child.Checked)
++selectedChildern;
}
}
}
if (selectedChildern > 1)
{
MessageBox.Show("Only one recipe per category can be selected at a time, please deselect the current recipe and try again.", "Too Many Recipes Selected", MessageBoxButtons.OK, MessageBoxIcon.Error);
e.Node.Checked = false;
e.Node.Parent.Checked = false;
Valid = false;
}
return Valid;
}
private bool CheckNumOfSelectedParents(TreeViewEventArgs e)
{
bool Valid = true;
int selectedParent = 0;
foreach (TreeNode root in tvRecipes.Nodes)
{
if (root.Checked)
++selectedParent;
}
if (selectedParent > 1)
{
MessageBox.Show("Only one recipe category can be selected at a time, please deselect the current recipe and try again.", "Too Many Recipes Selected", MessageBoxButtons.OK, MessageBoxIcon.Error);
e.Node.Checked = false;
Valid = false;
}
return Valid;
}
private void tvRecipes_BeforeCheck(object sender, TreeViewCancelEventArgs e)
{
if (e.Node.Parent != null && !e.Node.Parent.Checked)
e.Cancel = true;
else if (e.Node.Checked)
{
foreach (TreeNode child in e.Node.Nodes)
{
if (child.Checked)
e.Cancel = true;
}
}
}
private void tvRecipes_AfterCheck(object sender, TreeViewEventArgs e)
{
if (CheckNumOfSelectedParents(e))
{
if (e.Node.Parent != null && e.Node.Parent.Checked)
{
if (e.Node.Checked)
{
if (CheckNumOfSelectedChildern(e))
{
RecipeDs = RetrieveRecipe.FillRecipeDs(e.Node.Text);
DataBindControls();
}
}
else
{
RemoveLabelsFromLayout();
RemoveDataBindings();
RecipeDs.Clear();
this.Refresh();
}
}
}
}