如何基于从树视图中选择的子节点从数据库加载datagridview?例如如果选择了制造商名称(制造商名称是子节点),请加载该制造商的所有产品
String strConn = "Server = .\\SQLEXPRESS;Database = Northwind;Integrated
Security = SSPI;";
SqlConnection conn = new SqlConnection(strConn);
SqlDataAdapter da = new SqlDataAdapter("Select * from Suppliers", conn);
SqlDataAdapter daCategories = new SqlDataAdapter("Select * from
Categories", conn);
da.Fill(ds, "Suppliers");
daCategories.Fill(ds, "Categories");
ds.Relations.Add("Cat_Supply",
ds.Tables["Categories"].Columns["CategoryID"],
ds.Tables["Suppliers"].Columns["CategoryID"]);
foreach(DataRow dr in ds.Tables["Categories"].Rows)
{
TreeNode tn = new TreeNode(dr["CategoryName"].ToString());
foreach (DataRow drChild in dr.GetChildRows("Cat_Supply"))
{
tn.Nodes.Add(drChild["CompanyNamde"].ToString());
}
treeView1.Nodes.Add(tn);
}
答案 0 :(得分:0)
定义一个spearate子来加载DataGridView
,并使用一个参数(如您所愿)将类别名称或CategoryID(最好将其存储为TreeVeiwItem
中的标签) )。
C#:
private void LoadCategoryTest(Int32 CategoryID)
{
string cmdText = "SELECT ProductID, ProductName, CompanyName, Details, PurchasingCode FROM Products WHERE CategoryID = " + CategoryID + "; ";
DataSet ds;
DataTable dt;
ds = DatabaseAccess.GetQueryResults(cmdText);
if (ds.Tables.Count > 0)
{
dt = ds.Tables(0);
this.dgBends.DataSource = dt;
}
}
VB.NET:
Private Sub LoadCategoryTest(CategoryID As Int32)
Dim cmdText As String = "SELECT ProductID, ProductName, CompanyName, Details, PurchasingCode FROM Products WHERE CategoryID = " & CategoryID & "; "
Dim ds As DataSet
Dim dt As DataTable
ds = DatabaseAccess.GetQueryResults(cmdText)
If ds.Tables.Count > 0 Then
dt = ds.Tables(0)
Me.dgBends.DataSource = dt
End If
End Sub
很显然,将想要获取的任何内容都放入SQL查询中。
注意:我没有解释所使用的数据库功能,我认为这超出了这个问题的范围。要使用它,请仅使用树视图事件,例如NodeMouseClick
(或AfterSelect
等,这取决于您要实现的目标):
C#
private void TreeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
{
TreeNode n = (TreeNode)sender;
LoadDetail(n.Tag); // provided, you saved CategoryID into treenode tag
}
VB.NET:
Private Sub TreeView1_NodeMouseClick(sender As Object, e As TreeNodeMouseClickEventArgs) Handles TreeView1.NodeMouseClick
Dim n As TreeNode = CType(sender, TreeNode)
Call LoadDetail(n.Tag) ' provided, you saved CategoryID into treenode tag
End Sub
您可以对CategoryName字符串执行相同的操作。
注意:此基本示例不包括参数查询或绑定之类的内容。不过,它是有功能的。