我以这种方式填写组合框
KimyatEntities db = new KimyatEntities();
var BranchData = db.SpSelectBranch();
CBBranchName.DataSource = BranchData.ToList();
CBBranchName.DisplayMember = "Branch_Name";
CBBranchName.ValueMember = "Branch_ID";
我想通过linq查询获取组合框选择值
int BranchID=Convert.ToInt32(CBBranchName.SelectedValue);
var EmployeeData = from E in db.EmployeeTbls
join B in db.BranchTbls
on E.Branch_ID equals B.Branch_ID
where E.Branch_ID == BranchID
select new { E.Employee_Name, E.Hire_Date, B.Branch_Name };
DGVEmployee.DataSource = EmployeeData.ToList();
答案 0 :(得分:1)
试试这个:
var EmployeeData = from E in db.EmployeeTbls
join B in db.BranchTbls
on E.Branch_ID equals B.Branch_ID
where E.Branch_ID == BranchID
select new { Branch_ID= E.Branch_ID , Branch_Name= B.Branch_Name };
答案 1 :(得分:1)
我通过添加:
解决了这个问题1)属性
public int BranchSelectedID { get; set; }
2)班级
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 a construct that initiates the class
{
ID = BranchID;
Name = BranchName;
}
public override string ToString()
{
return Name; //this for text that appear in Combo Box control
}
}
3)绑定组合框代码
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));
}
}
之后绑定网格视图,具体取决于组合框选择的索引已更改
private void CBBranchName_SelectedIndexChanged(object sender, EventArgs e)
{
//The SelectedIndexChanged event
int SelectedBranch = CBBranchName.SelectedIndex;
BranchItem Selected = CBBranchName.Items[SelectedBranch] as BranchItem;
if (Selected!=null)
{
BranchSelectedID = Selected.ID;
}
DGVEmployee.Rows.Clear();
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)
{
DataGridViewRow row = new DataGridViewRow();
row.CreateCells(DGVEmployee);
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);
}
}
}