如何将数据表转换为列表<字符串>然后将其与文本框值进行比较
本文关键字:文本 比较 然后 转换 数据表 列表 字符串 | 更新日期: 2023-09-27 17:55:14
我有一个数据表 -> "检查产品(字符串 ID)",其中字符串 ID 是用于获取该发票的产品 ID
现在我想将其与文本框值进行比较。
我已经尝试了它的代码。
我的数据逻辑:-
public DataTable CheckProduct(String id)
{
DataTable dt = new DataTable();
SqlConnection sqlconnection;
sqlconnection = new SqlConnection(@" Database Connection String");
sqlconnection.Open();
SqlCommand cmd = new SqlCommand("checkproduct", sqlconnection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@inv_id", SqlDbType.VarChar).Value = int.Parse(id);
DataSet dtset = new DataSet();
SqlDataAdapter adpt = new SqlDataAdapter(cmd);
adpt.Fill(dtset);
dt = dtset.Tables[0];
return dt;
}
我的业务逻辑:-
public List<String> CheckProduct(String id)
{
SPDatalogic sp = new SPDatalogic(); //datalogic class
DataTable dt = new DataTable() ;
dt = sp.CheckProduct(id);
List<String> list = new List<String>();
SPBusinesslogic ab = new SPBusinesslogic(); //businesslogic class
String pro;
pro =ab.CheckProduct(id).ToString();
list.Add(pro);
return list;
}
我的表示层:-
string id = invoice_no_textbox.Text;
SPBusinesslogic ab = new SPBusinesslogic(); //businesslogic class
List<String> id_list = new List<String>();
id_list = ab.CheckProduct(id); //passing invoice_no as string id
if (id_list.Any(x => x.Equals(invoice_no_textbox.Text)))
{
MessageBox.Show("the product already exist");
}
假设您的发票 ID 的字段名称称为"invoice_id",我会将 CheckProduct 的代码重写为
public List<String> CheckProduct(String id)
{
SPDatalogic sp = new SPDatalogic(); //datalogic class
DataTable dt = sp.CheckProduct(id);
List<String> list = new List<String>();
foreach (DataRow dr in dt.Rows)
{
list.Add(dr["invoice_id"].ToString());
}
return list;
}
在您的代码中,您递归调用 CheckProduct 方法再次传递发票的 ID,并且似乎不是摆脱该循环的方法。相反,发票的产品列表已从上次对 SPDatalogic 类的调用中得知。所以你只需要把它们添加到你的列表中
同样在DataLogic类中,参数的声明中可能存在错误。 如果@inv_id是整数类型,则不要将参数声明为 VarChar
cmd.Parameters.Add("@inv_id", SqlDbType.Int).Value = int.Parse(id);
最后一点,我不明白当你的ID显然是数字时,你为什么要使用List<string>
。这会导致类型从字符串到 int 的持续转换,反之亦然。您只需检索List<int>
并仅转换文本框的输入。