我遇到了使用组合框删除数据的问题。错误提示我,我不知道如何解决它。任何人都可以帮助我吗?
private void btnDel_Click(object sender, EventArgs e)
{
using (testEntities Setupctx = new testEntities())
{
var Lo = Convert.ToInt16(cbLocationData.SelectedValue);
var DeleteLocation = (from delLocation in Setupctx.locations
where delLocation.Location1 == Lo
select delLocation).Single();
Setupctx.DeleteObject(DeleteLocation);
Setupctx.SaveChanges();
this.Delete_Location_Load(null, EventArgs.Empty);
MessageBox.Show("Selected Shift Timing Has Been Deleted.");
}
}
部分where delLocation.Location1 == Lo
向我显示错误
运算符'=='不能应用于'string'和'short'类型的操作数。“。
非常感谢您的帮助。
以上问题的答案如下:
private void btnDel_Click(object sender, EventArgs e)
{
using (testEntities Setupctx = new testEntities())
{
string selectLo = cbLocationData.SelectedItem.ToString();
var DeleteLocation = (from delLocation in Setupctx.locations
where delLocation.Location1 == selectLo
select delLocation).SingleOrDefault();
if (DeleteLocation != null)
{
Setupctx.DeleteObject(DeleteLocation);
Setupctx.SaveChanges();
cbLocationData.SelectedIndex = -1;
this.Delete_Location_Load(null, EventArgs.Empty);
MessageBox.Show("Selected Shift Timing Has Been Deleted.");
}
}
}
答案 0 :(得分:2)
这意味着您无法比较 delLocation.Location1
和Lo
,因为它们具有不同的数据类型。尝试:
where delLocation.Location1.Equals(Lo.ToString())
答案 1 :(得分:2)
显然Location1
是string
,无法使用short
直接与==
进行比较。不要将Lo
转换为short
,然后转换回string
,请尝试:
var Lo = (string)cbLocationData.SelectedValue;
答案 2 :(得分:1)
错误说您正在尝试将字符串与Int16进行比较。因为我们已经知道Lo是一个Int16,所以delLocation.Location1必须是字符串。因此,要解决此问题,请删除Convert.ToInt16()
(因为下拉列表的SelectedValue
为字符串),如下所示:
private void btnDel_Click(object sender, EventArgs e)
{
using (testEntities Setupctx = new testEntities())
{
var Lo = Convert.ToString(cbLocationData.SelectedValue);
var DeleteLocation = (from delLocation in Setupctx.locations
where delLocation.Location1 == Lo
select delLocation).Single();
Setupctx.DeleteObject(DeleteLocation);
Setupctx.SaveChanges();
this.Delete_Location_Load(null, EventArgs.Empty);
MessageBox.Show("Selected Shift Timing Has Been Deleted.");
}
}
如果您收到错误“序列不包含任何元素”,则表示您的查询未返回任何结果,并且您无法对空序列执行Single()
。您可以使用SingleOrDefault()
,然后检查值是否为null,如下所示:
private void btnDel_Click(object sender, EventArgs e)
{
using (testEntities Setupctx = new testEntities())
{
var Lo = Convert.ToString(cbLocationData.SelectedValue);
var DeleteLocation = (from delLocation in Setupctx.locations
where delLocation.Location1 == Lo
select delLocation).SingleOrDefault();
if (DeleteLocation != null)
{
Setupctx.DeleteObject(DeleteLocation);
Setupctx.SaveChanges();
this.Delete_Location_Load(null, EventArgs.Empty);
MessageBox.Show("Selected Shift Timing Has Been Deleted.");
}
}
}