我有一个DataSet
,其中有3个表Categories
,Items
和Products
。我可以单独访问它们。但我希望将它们绑定在3个不同的ComboBoxes
中,以便更改类别反映项目和更改项目反映产品。我想这可能会创建表之间的关系。请帮帮我。
答案 0 :(得分:0)
你可以通过Dataset实现这一点。请参考这个并尝试在你的代码中实现
// Define the relationship between Categories and Products.
DataRelation relat = new DataRelation("CatProds",
ds.Tables["Categories"].Columns["CategoryID"],
ds.Tables["Products"].Columns["CategoryID"]);
// Add the relationship to the DataSet.
ds.Relations.Add(relat);
答案 1 :(得分:0)
有一些束方法可以使用ADO.NET数据集为此猫设置外观,但您可以使用DataSet.Relations
建立数据表之间的关系。查看MSDN documentation了解详情。
以下是您所概述的关系的一个示例,并且只是沿着一条可能的路径走得太远,以便给出您的想法:
var ds = new DataSet();
// Add the Categories table with a CategoryID column, and add a few rows to it.
var categories = ds.Tables.Add("Categories");
var categoryIDColumn = categories.Columns.Add("CategoryID", typeof(int));
categories.Rows.Add(new object[] { 1 });
categories.Rows.Add(new object[] { 2 });
categories.Rows.Add(new object[] { 3 });
// Add the Items table with ItemID & CategoryID (FK) columns, and add a few Categories-relatable rows to it.
var items = ds.Tables.Add("Items");
var itemIDColumn = items.Columns.Add("ItemID", typeof(int));
var itemCategoryIDColumn = items.Columns.Add("CategoryID", typeof(int));
items.Rows.Add(new object[] { 11, 1 });
items.Rows.Add(new object[] { 12, 2 });
items.Rows.Add(new object[] { 13, 3 });
// Add the Products table with ProductID & ItemID (FK) columns, and add a few Items-relatable rows to it.
var products = ds.Tables.Add("Products");
var productIDColumn = products.Columns.Add("ProductID", typeof(int));
var productItemIDColumn = products.Columns.Add("ItemID", typeof(int));
products.Rows.Add(new object[] { 21, 11 });
products.Rows.Add(new object[] { 22, 12 });
products.Rows.Add(new object[] { 23, 13 });
// Add the FK relationships (or data relations as it were).
var categoryItemsRelation = ds.Relations.Add("FK_CategoryItems", categoryIDColumn, itemCategoryIDColumn);
var itemProductsRelation = ds.Relations.Add("FK_ItemProducts", itemIDColumn, productItemIDColumn);
// Run through an example of a selected ID in the categories dropdown.
int selectedCategoryID = 1;
var selectedCategory = categories.Select(String.Format("CategoryID = {0}", selectedCategoryID))[0];
var filteredItems = selectedCategory.GetChildRows(categoryItemsRelation);
Console.WriteLine("selectedCategoryID == {0}", selectedCategoryID);
Console.WriteLine("selectedCategory[categoryIDColumn] == {0}", selectedCategory[categoryIDColumn]);
foreach (var childItem in filteredItems)
{
Console.WriteLine("filteredItems includes:");
Console.WriteLine(
"\t{0} : {1}, {2} : {3}",
itemIDColumn.ColumnName,
childItem[itemIDColumn],
itemCategoryIDColumn.ColumnName,
childItem[itemCategoryIDColumn]);
}
// ...and so forth.