c# - c# 填充ComboBox的函数
问题描述
我想在 ClassProducts.cs 文件中创建一个函数,当我调用该函数时,它应该返回该 ComboBox 的值和标签。
ComboBox 控件在 ViewProducts 窗体中,功能在 ClassProducts.cs 类中。函数接受 1 个名为 Cat_ID 的参数
class ClassProducts
{
public DataTable FillSubCats(int catID)
{
DataTable items = new DataTable();
SqlCommand cmdFillSubCatL1 = new SqlCommand("SELECT * FROM tblProductCategories WHERE Cat_ParentCat =" + catID, con);
con.Open();
SqlDataReader sda = cmdFillSubCatL1.ExecuteReader();
while (sda.Read())
{
ComboboxItem item = new ComboboxItem();
item.Text = (sda["Cat_Name"]).ToString();
item.Value = (sda["Cat_ID"]).ToString();
items.Load(sda);
}
sda.Dispose();
sda.Close();
con.Close();
return items;
}
}
我想要 ClassProducts 文件中的一个函数,它将填充 ViewProducts.cs 表单中的 ComboBoxes。每当调用函数时,它都应将组合框项返回到调用文件。
我试过这个功能,但它不起作用。
请帮忙。谢谢你。
解决方案
这很可能是由于您没有使用sqlparameters
. Cat_ParentCat
必须是一个int
字段,因此当您尝试使用带有字符串连接的查询时, nvarchar
会发生一个猫到字段,并且由于您没有catId
在查询中使用引号括起来,所以它会失败。在任何情况下使用 SQL 参数,也将帮助您避免 SQL 注入。尝试:
SqlCommand cmdFillSubCatL1 = new SqlCommand("SELECT * FROM tblProductCategories WHERE Cat_ParentCat =@catId", con);
cmdFillSubCatL1.Parameteres.Add("@catId",SqlDbType.Int).Value=catId;
...
编辑: 正确评论后,更好的查询应该是:
"SELECT Cat_Name,Cat_ID FROM tblProductCategories WHERE Cat_ParentCat =@catId"
最后,因为你想加载一个DataTable
不使用 Datareader 而是一个 dataAdapter:
...
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = cmdFillSubCatL1 ;
adapter.Fill(items );