我有一个列表框,在加载页面时,我想选择数据库中的选择/选项。自从我对列表框做任何事情以来已经有一段时间了,所以我对如何修复我的 GetClassification 函数的代码有点困惑,这正是为了做到这一点。目前,它只选择列表框中的一个值,而不管供应商 ID 与多个值相关联。
这是 GetClassification 函数的代码:
protected void GetClassification(int VendorId)
{
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["AbleCommerce"].ToString()))
{
SqlCommand cmd = new SqlCommand("SELECT uidClassification FROM Baird_Vendors_Extension WHERE uidVendor = @VendorId", cn);
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add(new SqlParameter("@VendorId", VendorId));
cn.Open();
using (IDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
vendorType.SelectedValue =reader["uidClassification"].ToString();
}
}
}
}
最佳答案
您必须循环所有项目并相应地设置Selected
-属性:
List<string> uidClassificationList = new List<string>();
using (IDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
int column = reader.GetOrdinal("uidClassification");
uidClassificationList.Add(reader.GetInt32( column ).ToString());
}
}
foreach(ListItem item in vendorType.Items)
item.Selected = uidClassificationList.Contains(item.Value);
除此之外,如果第二个参数是 int
,您应该小心使用带有两个参数的 SqlParameter
构造函数,如下所示:
md.Parameters.Add(new SqlParameter("@VendorId", VendorId));
VendorId
将转换为 SqlDbType
和 different overload用来。相反,您应该明确指定 Value
:
md.Parameters.Add(new SqlParameter("@VendorId", SqlDbType.Int) { Value = VendorId });
编辑:这也记录在 remarks-section 中:
Use caution when you use this overload of the
SqlParameter
constructor to specifyinteger
parameter values. Because this overload takes a value of typeObject
, you must convert the integral value to an Object type when the value is zero, as the following C# example demonstrates.
Parameter = new SqlParameter("@pname", (object)0);
If you do not perform this conversion, the compiler assumes that you are trying to call the SqlParameter (string, SqlDbType) constructor overload.
所以这也行:
md.Parameters.Add(new SqlParameter("@VendorId", (object) VendorId));
关于c# - 根据数据库值预选列表框中的多个项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25995458/