一个简单的建立关联的demo
在做libraryMis时遇到的一个问题,我把这个问题缩小简化后,其实很简单,高手们表要笑。
两个表,经过范式化后,每个表中都有ID字段。
r1:
id name
=====================
001 jack
002 mike
003 lee
004 mary
r2:
id age
=====================
001 18
002 20
003 21
004 19
通过输入ID,显示出name和age
就这么简单的一个功能,我弄了半天。
问题总结:
1、对string.Format这个方法没有能灵活应用,导致走了弯路。
2、对DataRelation的成员没能足够熟练使用。
主要代码
private void button1_Click(object sender, System.EventArgs e)
{
try
{
//建立连接
OleDbConnection conn=new OleDbConnection();
conn.ConnectionString=@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\study\Relationship\Relationship.mdb;Persist Security Info=False";
conn.Open();
DataSet dt=new DataSet();
string id = textBox1.Text;
string r1 = string.Format(@"select * from r1 where id = '{0}'",id);//后面的值是输入的ID值,format方法是将指定的 String 中的每个格式项替换为相应对象的值的文本等效项。
string r2 = string.Format(@"select * from r2 where id = '{0}'",id);
OleDbDataAdapter odda1=new OleDbDataAdapter(r1,conn);
OleDbDataAdapter odda2=new OleDbDataAdapter(r2,conn);
odda1.Fill(dt,"r1");
odda2.Fill(dt,"r2");
DataRelation relid=dt.Relations.Add("id",dt.Tables["r1"].Columns["id"],dt.Tables["r2"].Columns["id"]);//建立关联,以各个表中的id列作为关联
foreach(DataRow prow in dt.Tables["r1"].Rows)
{
textBox2.Text=prow["name"].ToString();
foreach (DataRow crow in prow.GetChildRows(relid))
{
textBox3.Text=crow["age"].ToString();
}
}
}
catch(Exception s)
{
MessageBox.Show(s.Message);
}
}
this demo download
posted on 2006-02-13 00:08 pcuseman blog 阅读(314) 评论(0) 收藏 举报
浙公网安备 33010602011771号