hi i just upgraded to Framework 4.0 and added relationship foreign key to my database. I would like to join 2 table User and Staff
and return back to UI. Staff table has the UserId. Having to say that, whenever the user name is clicked on the datagridview, i would like to display out User and Staff data to all the textbox.
I do this using Tuple
public IEnumerable<Tuple<User, Staff>> Get()
{
using (qDataContext db = new qDataContext())
{
try
{
var r = from u in db.Users
join s in db.Staffs on u.Id equals s.UserId
select new Tuple<User, Staff>(u, s);
return r;
}
catch (Exception ex)
{
throw;
}
}
}
But in UI, how should i do the binding?
gvUser.DataSource = user.Get();
FYI, The gridview is just display the username. Staff table will store the password, datejoined fields..
By the way, do i still need to join tables since i have already added foreign key reference to the tables.. i am thinking of it should smart enough to return me User.Staff.Password
EDIT
this is what i found..
i have added relationship foreign key to my database.
and the code below is already able to return me User and Staff data as Staff.UserId is pointed to UserId
And i don have to use the TUPLE to return those object :)!!
public IEnumerable<User> Get()
{
using (ZebraDataContext db = new ZebraDataContext())
{
try
{
var r = from u in db.Users
select u;
//join s in db.Staffs on u.Id equals s.UserId
//select new Tuple<User, Staff>(u, s);
return r.ToList();
}
catch (Exception ex)
{
throw;
}
}
}
However, i have trouble when i bind to the GUI datagridview.
private void InitializeData()
{
gvUser.DataSource = user.Get();
}
This code able to shows me the User data. But how do i get back the Staff data when i do the gvUser_RowEnter
?
private void gvUser_RowEnter(object sender, DataGridViewCellEventArgs e) { if (e.RowIndex <= 0) return;
foreach (DataGridViewRow row in gvUser.SelectedRows)
{
User user = row.DataBoundItem as User;
txtName.Text = user.Name;
txtAddress.Text = user.Address;
txtPhone.Text = user.Phone;
txtPhone2.Text = user.Phone2;
txtRemark.Text = user.Remarks;
txtPassword.Text = user.Staffs.First().Password;
}
}
txtPassword.text = user.Staffs.First().Password
< == failed with this error
Cannot access a disposed object.
Object name: 'DataContext accessed after Dispose.'.
when i add watch the Staff object in User. i can see the data in the hidden ((User)(row.DataBoundItem)).Staffs.entities.Items this has the staff data ..
Rather than returning a Tuple
, wouldn't returning an anonymous object do the trick? It might look something like this:
var r = from u in db.Users
select new { u.Name,
u.Address,
...,
(from s in db.Staffs select s.Password where u.Id == s.UserId)
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With