且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

检索组合框选定值时出现问题

更新时间:2022-12-28 20:22:13

您所说的错误可能是由于您的第二个代码段中的最后一行。因为在分配数据源之前

,你必须强制执行查询以使用ToList()获取内存中的数据:



The error you are saying is probably due to that last line in your 2nd snippet. Because
just before assigning the datasource, you have to force query execution to get the data in memory using ToList():

DGVEmployee.DataSource = EmployeeData.ToList();


我通过添加



1)属性

I Solve the problem by adding

1) properties
public int BranchSelectedID { get; set; }





2)Calss





2) Calss

private class BranchItem
       {
          // I Take this class variable to take the Selected value from combo box control
           public int ID;
           public string Name;

           public BranchItem(int BranchID, string BranchName) //This is construct that initiate the Class
           {
               ID = BranchID;
               Name = BranchName;
           }

           public override string ToString()
           {
               return Name; //this for text that appear in Combo Box control
           }
       }





3)绑定组合盒代码





3) Bind combo Box code

void bindBranch_ComboBox()
       {
           db = new KimyatEntities();
           CBBranchName.Items.Clear();
           var BranchData = (from B in db.BranchTbls
                             select new { B.Branch_ID, B.Branch_Name }).ToList();
           foreach (var item in BranchData)
           {
               CBBranchName.Items.Add(new BranchItem(item.Branch_ID, item.Branch_Name));
           }

       }





之后绑定网格视图取决于组合Box选择的索引已更改





After that bind Grid View Depending on the Combo Box Selected Index Changed

private void CBBranchName_SelectedIndexChanged(object sender, EventArgs e)
       {

           int SelectedBranch = CBBranchName.SelectedIndex;

           BranchItem Selected = CBBranchName.Items[SelectedBranch] as BranchItem;
           if (Selected!=null)
           {
              BranchSelectedID = Selected.ID;
           }
           DGVEmployee.Rows.Clear();
           DataGridViewRow row = new DataGridViewRow();
           row.CreateCells(DGVEmployee);
           var EmployeeData = from E in db.EmployeeTbls
                              join B in db.BranchTbls
                              on E.Branch_ID equals B.Branch_ID
                              where E.Branch_ID == BranchSelectedID
                              select new { E.Employee_ID, E.Employee_Name, E.Hire_Date, B.Branch_Name };
           if (EmployeeData != null)
           {

               foreach (var item in EmployeeData)
               {
                   row.Cells[0].Value = item.Employee_ID;
                   row.Cells[1].Value = item.Employee_Name;
                   row.Cells[2].Value = item.Hire_Date;
                   row.Cells[3].Value = item.Branch_Name;
                   DGVEmployee.Rows.Add(row);
               }
           }
       }