我有两张桌子
EmpInf
EmpId,
EmpName,
Salary,
DepartNumber.
Dept
DeptNo,
Deptname,
我还有listview1
和dropdownlist1
绑定到EmpInf.EmpName
传递特定查询时
FilterControl.DataClasses1DataContext obj = new DataClasses1DataContext();
protected void DropDownList1_SelectedIndexChanged1(object sender, EventArgs e)
{
var a = from r in obj.EmpInfs join s in obj.Dept1s on r.DeptNumber equals s.DeptNo where r.EmpName == "'" + DropDownList1.SelectedValue + "'" select s;
ListView1.DataSource = a;
ListView1.DataBind();
}
每当我从下拉列表中选择一个特定名称时,它都会返回没有返回任何数据。我缺少哪些特定代码或者是否有其他错误?
答案 0 :(得分:1)
在SelectedIndexChanged1
中放置一个断点并查看SelectedValue
的值,以确保DropDownList1.SelectedValue
具有员工姓名。您也可以尝试DropDownList1.SelectedText
。
string selected = DropDownList1.SelectedValue.ToString();
// e = employee | d = department
var query =
from e in obj.EmpInfs
join d in obj.Dept1s on e.DeptNumber equals d.DeptNo
where e.EmpName == "'" + DropDownList1.SelectedValue + "'"
select d;
更改此行:
where e.EmpName == "'" + DropDownList1.SelectedValue + "'"
到这一个:
where e.EmpName == selected
好的,我在这里的最后一次尝试......在数据绑定之前执行此操作:
ListView1.DataSource = query.ToList();
答案 1 :(得分:0)
此处的问题很可能是您在Where子句中添加了搜索条件的单引号:
var a = from r in obj.EmpInfs
join s in obj.Dept1s on r.DeptNumber equals s.DeptNo
where r.EmpName == "'" + DropDownList1.SelectedValue + "'"
select s;
假设DropDownList1.SelectedValue是“Smith”,那么你生成的sql将沿着以下几行:
SELECT *
FROM <tables>
WHERE EmpName = ''Smith''
注意双单引号。要仔细检查这一点,请在生成查询后设置断点,然后在其上调用.ToString()以获取等效的TSQL。要解决此问题,请从LINQ查询中删除“'”,因为它将自动添加到字符串参数中:
var a = from r in obj.EmpInfs
join s in obj.Dept1s on r.DeptNumber equals s.DeptNo
where r.EmpName == DropDownList1.SelectedValue
select s;