在数据库中搜索只显示带有链接按钮的Gridivew中的名字和姓氏。
在第一张图片(1)中,我只搜索第一个名字,并显示名字和姓氏。 在第二张Image(2)中,我只搜索the中的第一个字符并显示它,但我显示它5次为什么?只想要一次?
这是我的代码
private void GetEmployee()
{
var db = new knowitCVdbEntities();
var employee = (from p in db.EMPLOYEES
where
p.firstname.Contains(TextBoxSearch.Text) ||
p.lastname.Contains(TextBoxSearch.Text) ||
p.position.Contains(TextBoxSearch.Text)
select p).ToList();
foreach (var vEmp in employee)
{
if (vEmp != null)
{
HiddenFieldID.Value = vEmp.employee_id.ToString();
if (Session["DataTableSearch"] != null)
{
_dt = (DataTable)Session["DataTableSearch"];
}
else
{
_dt.Columns.Add("Firstname");
_dt.Columns.Add("employeeId");
}
//_dt.Rows.Clear();
DataRow dr = _dt.NewRow();
dr["Firstname"] = vEmp.firstname+" "+vEmp.lastname;
dr["employeeId"] = vEmp.employee_id;
_dt.Rows.Add(dr);
Session["DataTableSearch"] = _dt;
GridViewDisplayName.DataSource = _dt;
GridViewDisplayName.DataBind();
}
}
}
答案 0 :(得分:0)
当你经历这个并运行它时, 它将保存旧的搜索,
所以你必须在开始时调用_dt.clear,这样理论上你每次只能得到一个结果:)
编辑 - 事实上,你的代码实际上已经清楚了,只是注释掉了,只是在错误的地方:)
答案 1 :(得分:0)
在foreach (var vEmp in employee)
行之前插入此权利:
_dt.Clear();
所以你的代码是:
private void GetEmployee()
{
var db = new knowitCVdbEntities();
var employee = (from p in db.EMPLOYEES
where
p.firstname.Contains(TextBoxSearch.Text) ||
p.lastname.Contains(TextBoxSearch.Text) ||
p.position.Contains(TextBoxSearch.Text)
select p).ToList();
_dt.Clear();
foreach (var vEmp in employee)
{
if (vEmp != null)
{
HiddenFieldID.Value = vEmp.employee_id.ToString();
if (Session["DataTableSearch"] != null)
{
_dt = (DataTable)Session["DataTableSearch"];
}
else
{
_dt.Columns.Add("Firstname");
_dt.Columns.Add("employeeId");
}
//_dt.Rows.Clear();
DataRow dr = _dt.NewRow();
dr["Firstname"] = vEmp.firstname+" "+vEmp.lastname;
dr["employeeId"] = vEmp.employee_id;
_dt.Rows.Add(dr);
Session["DataTableSearch"] = _dt;
GridViewDisplayName.DataSource = _dt;
GridViewDisplayName.DataBind();
}
}
}