开发者

Access different columns from LINQ resultset

I ha开发者_JS百科ve a query which returns multiple columns from the database using LINQ

var donors = from d2 in db.Donors
                 where d2.Status == "Pending"
                 select new { donorID = d2.donorID, bloodGroup = d2.bloodGroup, contactNo = d2.contactMobile, status = d2.Status };

now I want to display the results in different Labels accessing one column value from donors resultset.

ex:

Label1.Text = donorID; Label2.Text = bloodGroup; ...and so on

please help me achieve this.


If you're going to set a label to a value, you'll need a single record. Currently you're selecting a sequence of records. Let's suppose you're only interested in the first value. You could write:

var donors = from d2 in db.Donors
             where d2.Status == "Pending"
             select new { d2.donorID, d2.bloodGroup, 
                          contactNo = d2.contactMobile, status = d2.Status };

var firstDonor = donors.FirstOrDefault();
if (firstDonor != null)
{
    Label1.Text = firstDonor.donorID;
    Label2.Text = firstDonor.bloodGroup;
    // ...
}
else
{
    // There weren't any matching donors
}

If you want to display all the donor details, you'll want something more like a grid.


If you insist in keeping the labels, you could do something like this

var donors = from d2 in db.Donors
             where d2.Status == "Pending"
             select d2;

List<Donors> myDonors = donors.ToList();

        int x = 0;
        int y = 0;
        foreach (var donor in donors)
        {
            Label myLabel = new Label();
            myLabel.Top = x;
            myLabel.Left = y;
            myLabel.Text = donor.donorID.ToString();
            panel1.Controls.Add(myLabel);
            y += myLabel.Width + 5;

            myLabel = new Label();
            myLabel.Top = x;
            myLabel.Left = y;
            myLabel.Text = donor.blodGroup.ToString();
            panel1.Controls.Add(myLabel);
            y += myLabel.Width + 5;

            myLabel = new Label();
            myLabel.Top = x;
            myLabel.Left = y;
            myLabel.Text = donor.contactNo.ToString();
            panel1.Controls.Add(myLabel);
            y += myLabel.Width + 5;

            myLabel = new Label();
            myLabel.Top = x;
            myLabel.Left = y;
            myLabel.Text = donor.status.ToString();
            panel1.Controls.Add(myLabel);
            y += myLabel.Width + 5;


            y = 0;
            x += myLabel.Height + 5;
        }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜