我有一个TreeView
,其中填充了SQL Server数据库表中的数据,我想根据数据库中选定的项ID将数据插入其中,这是我的代码:
private void Form1_Load(object sender, EventArgs e)
{
TreeLoad();
}
// Connecting to Database and retieving data
private DataTable Select(int ID)
{
SqlConnection conn = new SqlConnection(@"server= M_SHAWAF\ORCHESTRATE; integrated security= true; database= FM");
conn.Open();
SqlCommand cmd = new SqlCommand("GetNodes2", conn);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter parameter = new SqlParameter("ID", ID);
parameter.SqlDbType = SqlDbType.Int;
cmd.Parameters.Add(parameter);
SqlDataAdapter ad = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
ad.Fill(dt);
return dt;
}
//Loading the treeView1
void TreeLoad()
{
DataTable dt = Select(0);
AddNodes(dt, treeView1.Nodes);
}
//Adding nodes to treeView1
void AddNodes(DataTable dt, TreeNodeCollection coll)
{
foreach (DataRow dr in dt.Rows)
{
TreeNode node = new TreeNode();
node.Text = dr[1].ToString();
coll.Add(node);
try
{
DataTable child = Select((int)dr[0]);
if (child.Rows.Count > 0)
{
AddNodes(child, node.Nodes);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
这是表格:
表格:
当我点击插入btn时,我希望获得所选节点的EmpID
(还有另一个窗体,其中包含新名称的文本框)。
GetNodes
存储过程:
create procedure GetNodes
@ID int
as
select
e.EmpID, e.EmpName
from
Employee e
where
isnull(e.ManagerID, 0) = @ID
return
答案 0 :(得分:1)
一种选择是将ID存储在每个节点的标签中。然后,您可以在单击按钮时通过调用treeView1.SelectedNode.Tag
来抓取它。
答案 1 :(得分:0)
您需要在树视图中循环每个节点,就像从数据库中填充它一样。
void SelectNodeOnTreeView(string EmpID, TreeNodeCollection NodeCollection)
{
if (NodeCollection.Count > 0)
{
foreach (TreeNode node in NodeCollection)
{
if (node.Text == EmpID)
{
treeView1.SelectedNode = node;
break;
}
SelectNodeOnTreeView(EmpID, node.Nodes);
}
}
}
答案 2 :(得分:0)
您可以创建一个自己的TreeNode类来实现TreeNode
,但也可以添加其他必填字段,例如id
:
class myTreeNode : TreeNode
{
public int id;
public myTreeNode(string text, int id)
{
this.Text = text;
this.id = id;
}
}
然后在AddNodes
循环的foreach
方法中,而不是:
TreeNode node = new TreeNode();
node.Text = dr[1].ToString();
做这样的事情:
TreeNode node = new myTreeNode(dr[1].ToString(), (int)dr[0]); //don't know where you're storing your ID, here I'm assuming it's in dr[0].
这样,您应该能够通过执行以下操作来获取所选节点的ID:
myTreeNode selectedNode = (myTreeNode)treeview1.SelectedNode;
int selectedID = selectedNode.id;