There are a couple things going on here:
1) You have already declared
SqlCommand cmd
at the class level, so you do not need to declare it again (you should get an exception for this). Just assign the
cmd
variable.
cmd = new SqlCommand("insert into treenodes values(" + textBox1.Text + ");", con);
2) When inserting strings into sql, the value must be surrounded by single quote marks (you should get an exception for this).
cmd = new SqlCommand("insert into treenodes values('" + textBox1.Text + "');", con);
Note: It would be better to use
SqlCommand.Parameters
to add the values, then they would get wrapped appropriately if needed. It is also good practice for avoiding sql injection attacks.
3) Since you do not specify which column to insert into, the value will always insert into the first column. When you retrieve the data:
cmd = new SqlCommand("SELECT parentNode,childNode FROM treenodes", con);
if the parentNode is the first column, then all the values you entered will be in that column and the childNode column will be full of
NULL
values. To specify which column to insert values to:
cmd = new SqlCommand("insert into treenodes (parentNode) values('" + textBox1.Text + "');", con);
or, if you enter a child node, you will want to specify who the parent node is:
cmd = new SqlCommand("insert into treenodes (parentNode, childNode) values('" + treeView1.SelectedNode.Text + "','" + textBox1.Text + "');", con);
4) The way you are looping through the results, you are adding all the values as if they were parents, you are not adding the child nodes to the proper parent.
while (dr.Read())
{
treeView1.Nodes.Add(dr.GetValue(0).ToString());
}
This should give you a few things to look at.