根据数据库值预先选择列表框中的多个项目

时间:2014-09-23 12:44:59

标签: c# asp.net listbox

我有一个列表框,在加载页面时,我想选择数据库中的选项/选项。已经有一段时间了,因为我已经对列表框做了任何事情,所以我对如何修复我的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();
            }
        }
    }
}

2 个答案:

答案 0 :(得分:2)

您必须循环所有项目并相应地设置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);

除此之外,你应该小心SqlParameter构造函数,它带有两个参数,如果第二个是int,就像这里:

md.Parameters.Add(new SqlParameter("@VendorId", VendorId));

VendorId将投放到SqlDbType并使用different overload。相反,您应该明确指定Value

md.Parameters.Add(new SqlParameter("@VendorId", SqlDbType.Int) { Value = VendorId });

修改remarks-section

中也记录了这一点
  

使用SqlParameter构造函数的此重载时请小心   指定integer参数值。因为这个过载需要一个   类型Object的值,必须将整数值转换为Object   当值为零时键入,如下面的C#示例所示。

Parameter = new SqlParameter("@pname", (object)0); 
  

如果你不这样做   执行此转换,编译器假定您正在尝试   调用SqlParameter(string,SqlDbType)构造函数重载。

所以这也可以:

md.Parameters.Add(new SqlParameter("@VendorId", (object) VendorId));

答案 1 :(得分:0)

检查ListBox的SelectionMode属性是否为Multiple,这将启用多项选择。

e.g

<asp:ListBox ID="ListBox1" runat="server" SelectionMode="Multiple"></asp:ListBox>
相关问题