C#(.NET 3.5)
我有一个带有两个表的SQLite数据库 - employees(第一列是id INTEGER PRIMARY KEY)和holiday(id INTEGER - 表示员工的ID;开始DATE,结束DATE - 不言自明)。
我的表单包含文本框,复选框等以表示员工详细信息 - 但是我还想要一个列表框,列出当前所选员工的所有假期。
所以我需要一个数据关系,因为列表框应该只显示一个人当时的假期(两个数据表上的ID需要匹配)。
var command = new SQLiteCommand("SELECT * FROM employees; SELECT * FROM holidays");
var connection=new SQLiteConnection(@"data source=C:\employees.db");
command.Connection = connection;
SQLiteDataAdapter adapter = new SQLiteDataAdapter(command);
DataSet d = new DataSet();
adapter.Fill(d);
DataTable employees = d.Tables[0];
// [...]
// here I'm databinding my textboxes etc. to various columns
// of the employees data table - this works fine, navigation works well etc.
// [...]
DataTable holidays = d.Tables[1];
DataRelation relation;
DataColumn master = employees.Columns[0];
DataColumn slave = holidays.Columns[0];
relation = new DataRelation("relation", master, slave);
d.Relations.Add(relation);
var dsView = holidays.DefaultView;
listBox1.DisplayMember = "holidays.relation.start"; // <= it wouldn't look good like that of course, but I just want to get the thing to work for now
listBox1.DataSource = dsView;
答案 0 :(得分:2)
首先,您已将变量命名为employees和holidays,但这确实意味着数据集中的表名称已更改;它们仍然设置为默认名称,在您的情况下是表和table1。 (他们通常是桌子,桌子1 ...桌子N) 这意味着您的显示成员属性应如下所示:
listBox1.DisplayMember = "table.relation.start";
此外,请确保您数据绑定到数据集本身而不是数据集中的假期表,如下所示:
listBox1.DataSource = d;
有了这两个变化,你会发现它有效; this.BindingContext应该有助于导航父记录,因为您会注意到当时只显示了一组子(假日)结果。
完成修改后的代码如下:
var command = new SQLiteCommand("SELECT * FROM employees; SELECT * FROM holidays");
var connection=new SQLiteConnection(@"data source=C:\employees.db");
command.Connection = connection;
SQLiteDataAdapter adapter = new SQLiteDataAdapter(command);
DataSet d = new DataSet();
adapter.Fill(d);
DataTable employees = d.Tables[0];
// [...]
// here I'm databinding my textboxes etc. to various columns
// of the employees data table - this works fine, navigation works well etc.
// [...]
DataTable holidays = d.Tables[1];
DataRelation relation;
DataColumn master = employees.Columns["id"];
DataColumn slave = holidays.Columns["employeeid"];
relation = new DataRelation("relation", master, slave);
d.Relations.Add(relation);
listBox1.DisplayMember = "table.relation.start"; // <= it wouldn't look good like that of course, but I just want to get the thing to work for now
listBox1.DataSource = d;