关于设置TreeView数据源代码的问题
下面是设置TreeView数据的代码,现在想改为通过控件(DataSet,BindingSource,TableAdapter)调资料,即不用getDataset,应怎么更改代码,特别是dv.Table = dsDept.Tables[ "dept "]这行,我老在这行出错。如果哪位网友有更好的方法希望能贴出来。
dsDept = getDataset();
setTreeData(tvTree.Nodes, "0 ");//从根开始
private DataSet getDataset()
{
string strSelect = "SELECT [AutoID],[deptID],[deptName] ,[parentID] " +
"FROM [erpdata].[dbo].[ Department] ";
SqlConnection sqlcon = new SqlConnection(SqlConntionString);
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(strSelect, sqlcon);
da.Fill(ds, "Dept ");
return ds;
}
private void setTreeData(TreeNodeCollection Nds, string pId)
{
DataView dv = new DataView();
TreeNode tmpNd;
string intId;
dv.Table = dsDept.Tables[ "dept "];
dv.RowFilter = "deptID= ' " + pId + " ' ";
foreach (DataRowView drv in dv)
{
tmpNd = new TreeNode();
intId = drv[ "deptID "].ToString();
tmpNd.Name = intId;
tmpNd.Text = drv[ "deptName "].ToString();
Nds.Add(tmpNd);
setTreeData (tmpNd.Nodes, intId);
}
}
------解决方案--------------------//利用Nodes.Find()寻找父节点
//参考如下代码
private void button1_Click(object sender, EventArgs e)
{
OleDbConnection vOleDbConnection = new OleDbConnection(
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Temp\\temp.mdb ");
string vSqlCommandText = "select * from tree ";
vOleDbConnection.Open();
OleDbCommand vOleDbCommand = new OleDbCommand(vSqlCommandText, vOleDbConnection);
OleDbDataReader vOleDbDataReader = vOleDbCommand.ExecuteReader();
while (vOleDbDataReader.Read())
{
TreeNode[] vParentNodes =
treeView1.Nodes.Find(vOleDbDataReader.GetString(2), true);
if (vParentNodes.Length > 0)
vParentNodes[0].Nodes.Add(vOleDbDataReader.GetString(1),
vOleDbDataReader.GetString(1));
else treeView1.Nodes.Add(vOleDbDataReader.GetString(1),
vOleDbDataReader.GetString(1));
}
}