![](/img/trans.png)
[英]I want to check the value entered in Data gridview is already exist or not?
[英]How to check if the entered data is exist in SQLite?
我的PosMain
SQLite数据库中有一个表名称Staff
,该表名称包含StaffId
, StaffName
属性
我有一个名为LoginWindows
函数的窗口,如带有一个名为txtStaffId
文本框的Login
页面。
我想要的是当用户在txtStaffId
中输入其ID时,系统将检查其ID是否存在于Staff
表中。 如果存在,则系统将转到我的主窗口PosWindows
并获取其数据,例如StaffId
和StaffName
。
问题是我没有找到一种方法来检查txtStaffId
的Id密钥是否存在。
我使用了这段代码,但是由于我使用的是FirstOrDefault
因此它仅获取表中的第一个数据。 该代码位于我的业务层,称为SalesmanBo
public int GetStaffId(int staffId)
{
try
{
using (PosMainDBContext db = new PosMainDBContext())
{
return db.Staff.Select(s => s.StaffId).FirstOrDefault();
}
}
catch (Exception ex)
{
CustomExceptionHandling customExceptionHandling = new CustomExceptionHandling();
customExceptionHandling.CustomExHandling(ex.ToString());
return 0;
}
}
这是我在LoginWindows
上登录的代码
private void txtStaffId_KeyDown(object sender, KeyEventArgs e)
{
try
{
SalesmanBO salesmanBO = new SalesmanBO();
Staff staff = new Staff();
if (e.Key == Key.Return)
{
if (!string.IsNullOrEmpty(txtStaffId.Text))
{
int salesmanId = Int32.Parse(txtStaffId.Text);
int staffId = salesmanBO.GetStaffId(staff.StaffId);
if (salesmanId == staffId )
{
PosWindows posWindows = new PosWindows();
posWindows.Show();
this.Close();
}
else
{
MessageBox.Show("ID not Valid", "Alert", MessageBoxButton.OK, MessageBoxImage.Information);
}
}
else
{
MessageBox.Show("Please Key In your ID", "Alert", MessageBoxButton.OK, MessageBoxImage.Information);
}
}
}
catch (Exception ex)
{
CustomExceptionHandling customExceptionHandling = new CustomExceptionHandling();
customExceptionHandling.CustomExHandling(ex.ToString());
}
}
你能帮我吗 我是WPF和SQLITE的新手
您提供的代码中有很多错误的地方。 例如,您在GetStaffId
方法中传递了staffId
,但从未使用过。 我建议您检查Staff
实体而不是仅检查staffId
因为它可以进一步使用。 检查以下改进版本以了解一些想法。
public Staff GetStaffById(int staffId)
{
try
{
using (PosMainDBContext db = new PosMainDBContext())
{
return db.Staff.Where(s => s.StaffId == staffId).FirstOrDefault();
}
catch (Exception ex)
{
CustomExceptionHandling customExceptionHandling = new CustomExceptionHandling();
customExceptionHandling.CustomExHandling(ex.ToString());
return null; // changed return 0 to return null
}
}
}
在txtStaffId_KeyDown
事件中更改以下代码行。
if (!string.IsNullOrEmpty(txtStaffId.Text))
{
int salesmanId = Int32.Parse(txtStaffId.Text);
staff = salesmanBO.GetStaffById(salesmanId);
if (staff!=null) // no need to check salesmanId == staff.StaffId as we already checked while querying it.
{
PosWindows posWindows = new PosWindows();
posWindows.Show();
this.Close();
}
else
{
MessageBox.Show("ID not Valid", "Alert", MessageBoxButton.OK, MessageBoxImage.Information);
}
}
UPDATE
在GetStaffById
方法中,将返回类型更改为return null
;
无需创建新的Staff
实例。 更改Staff staff = new Staff();
给Staff staff;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.