使用Linq以C#Windows形式将数据从数据库加载到RichTextBox

时间:2018-12-27 00:47:30

标签: c# winforms linq richtextbox

enter image description here

我正在尝试使用Linq在我的c#Windows窗体Project中将数据从数据库加载到RichTextBox(如图所示)。

我不知道我是否做对了,因为数据没有加载到RichTextBox中。请帮忙。

这就是我要尝试的方式:

 string idNr = txtIdcardNr.Text.Trim();

 var CheckIfIdCardExist = (from u in db.Customer
                           where u.IdentityCardNr == idNr
                           select u).FirstOrDefault();
     if(CheckIfIdCardExist != null)
     {
       String template =
       @"Date\t\t{0}
       Notes\t\t{1}
       Staff\t\t{2}
       *********\t\t{3}";
              var notes = (from u in db.CustomerNotes
                           join em in db.Employee on u.StaffId equals em.EmployeeId
                           where u.CustomerId == CheckIfIdCardExist.CustomerId
                           select new {
                                         Date = u.NoteDate,
                                         notes = u.Notes,
                                         employee = em.FirstName + " " + em.LastName


                                     }).ToList();
                    foreach(var n in notes)
                    {
                        richTextBox1.Text = string.Format(template, n.Date, n.notes, n.employee);
                    }

1 个答案:

答案 0 :(得分:2)

我在这里取得了长足的进步,猜测主要问题是您看不到所有笔记,只是最后一个。

     var notes = (from u in db.CustomerNotes
                       join em in db.Employee on u.StaffId equals em.EmployeeId
                       where u.CustomerId == CheckIfIdCardExist.CustomerId
                       select new {
                                     Date = u.NoteDate,
                                     notes = u.Notes,
                                     employee = em.FirstName + " " + em.LastName


                                 });

     StringBuilder sb = new StringBuilder();
     foreach(var n in notes)
     {
        sb.AppendFormat(template, n.Date, n.notes, n.employee);
        sb.Append("\n");
     }
     richTextBox1.Text = sb.ToString();