我有要求我在DataGridView中显示Master-Detail信息。
我已将foriegn密钥关系添加到数据集。但是,细节网格不会根据主人的选择来自我掠过。我不知道我在这里缺少什么!
只是为了验证关系是否存在,我已经使用DataGrid检查了它们。我出现在那里。
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
DataSet CreateTableAndFill()
{
DataSet ds = new DataSet();
DataTable Header = ds.Tables.Add("Header");
DataTable Line = ds.Tables.Add("Line");
DataColumn dataColumn = Header.Columns.Add("ID", typeof(int));
dataColumn.AutoIncrement = true;
dataColumn.AutoIncrementSeed = 1;
Header.Columns.Add("Name", typeof(string));
Line.Columns.Add("ID", typeof(int));
Line.Columns.Add("Phone", typeof(string));
DataRelation dataRelation = new DataRelation("ID_FK", Header.Columns["ID"], Line.Columns["ID"]);
ds.Relations.Add(dataRelation);
Header.Rows.Add(null, "Huzaiafa");
Header.Rows.Add(null, "Arthur");
Line.Rows.Add(1, "4253068516");
Line.Rows.Add(1, "4252746864");
Line.Rows.Add(2, "5654034");
Line.Rows.Add(2, "12563");
return ds;
}
private void button1_Click(object sender, EventArgs e)
{
DataSet ds = CreateTableAndFill();
dataGridView1.DataSource = ds;
dataGridView2.DataSource = ds;
dataGridView1.DataMember = "Header";
dataGridView2.DataMember = "Line";
}
}
}
即使从msdn应用了漫游,它也无效!结果相同。
private void button1_Click(object sender, EventArgs e)
{
DataSet ds = CreateTableAndFill();
BindingSource masterBindingSource = new BindingSource();
BindingSource detailsBindingSource = new BindingSource();
masterBindingSource.DataSource = ds;
detailsBindingSource.DataSource = masterBindingSource.DataSource;
masterBindingSource.DataMember = "Header";
detailsBindingSource.DataMember = "Line";
dataGridView1.DataSource = masterBindingSource;
dataGridView2.DataSource = detailsBindingSource;
}
答案 0 :(得分:2)
进行以下更改:
Header.Rows.Add(1, "Huzaiafa");
Header.Rows.Add(2, "Arthur");
detailsBindingSource.DataSource = masterBindingSource;
detailsBindingSource.DataMember = "ID_FK";
答案 1 :(得分:2)
您将收到很多MSDN文章Walkthrough: Creating a Master/Detail Form Using Two Windows Forms DataGridView Controls。
它显示了你想要做的事情。
您将看到该示例将DataSet绑定到绑定到主DGV的BindingSource,并且详细信息DGV绑定到另一个BindingSource,该BindingSource本身被发现到主BindingSource。这就是你如何获得DGV之间的主 - 细节关系。
<强>更新强>
这将取代你的button1_Click:
private void button1_Click(object sender, EventArgs e) {
BindingSource masterBindingSource = new BindingSource();
BindingSource detailsBindingSource = new BindingSource();
masterBindingSource.DataSource = CreateTableAndFill();
masterBindingSource.DataMember = "Header";
dataGridView1.DataSource = masterBindingSource;
detailsBindingSource.DataSource = masterBindingSource;
detailsBindingSource.DataMember = "ID_FK";
dataGridView2.DataSource = detailsBindingSource;
}