save text fields to an Array (and pull data from the Array) when using treeview in c#
Ok, I have a treeview which I am using to display a number of nodes. I wish to attach data (three textbox fields) to each node but I do not want to show it in the tree. I wish to save the data to a string[] Array if possible. I want the data in the boxes to save to the Arrays when I click on a new node in the tree and pull the information from the Arrays for the new node.
For some reason the code I have does not work. It doesn't save the information and sometimes it just shows random data in the text boxes as I click about. The code is:
These are global variables within the form:
string[] desc1;
s开发者_运维问答tring[] desc2;
string[] desc3;
private void treeView1_BeforeSelect(object sender, TreeViewEventArgs e)
{
// save the entered text into the local variables
desc1[treeView1.SelectedNode.Index] = textBox4.Text;
desc2[treeView1.SelectedNode.Index] = textBox5.Text;
desc3[treeView1.SelectedNode.Index] = textBox6.Text;
}
private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
// update labels
label23.Text = treeView1.SelectedNode.Text.ToString();
label24.Text = (treeView1.SelectedNode.Index + 1).ToString();
// enable all textbox fields
textBox4.Enabled = true;
textBox5.Enabled = true;
textBox6.Enabled = true;
// clear all textbox fields
textBox4.Text = null;
textBox5.Text = null;
textBox6.Text = null;
// if parent is selected then show as unselected - if not update text fields
if (treeView1.SelectedNode.Text.ToString() == "Parent Name")
{
label23.Text = "Unselected";
label24.Text = "Unselected";
textBox4.Enabled = false;
textBox5.Enabled = false;
textBox6.Enabled = false;
}
else
{
// show the information from the array in the text fields
textBox4.Text = desc1[treeView1.SelectedNode.Index];
textBox5.Text = desc2[treeView1.SelectedNode.Index];
textBox6.Text = desc3[treeView1.SelectedNode.Index];
}
}
Anyone have an idea of what I can do? I have trawled google now for 24hours with no luck. Thanks!
The TreeNodes
have a Tag
property that you can use to attach any sort of data that you would like.
You would use it like this:
// To set the data:
myTreeNode.Tag = new string[] { "1", "2", "3" };
// To read the data:
var data = myTreeNod.Tag as string[];
The arrays are not initalized.
Replace all your references to SelectedNode
to be TreeViewEventArgs.Node
instead.
Code example:
private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
// update labels
label23.Text = e.Node.Text.ToString();
label24.Text = (e.Node.Index + 1).ToString();
// etc etc...
}
精彩评论