【问题标题】:Pre-select multiple items in listbox based on database values根据数据库值预选列表框中的多个项目
【发布时间】:2014-09-23 21:15:04
【问题描述】:

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

【问题讨论】:

  • 您不需要@ClassId,因为您没有在SqlCommand 中声明此参数。
  • 我正在使用 ASP.NET。

标签: c# asp.net listbox


【解决方案1】:

您必须循环所有项目并相应地设置Selected-property:

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

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

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

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

所以这也可以:

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

【讨论】:

  • 上面唯一的问题是,对于 while 循环内的行,我看到这个错误: System.Data.IDataRecord.GetString(int) 的最佳重载匹配有一些无效参数。 ..
  • @galifrey1212:那么它实际上是一个int。我更喜欢Get... 方法,因为如果我错误地使用了错误的数据类型并且我没有得到隐式转换(比如来自DateTime,包括本地化问题),它们会很快失败。请注意,我已经添加了答案。
  • 好的,我应用了更改并且效果很好。非常感谢:)
【解决方案2】:

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

例如

<asp:ListBox ID="ListBox1" runat="server" SelectionMode="Multiple"></asp:ListBox>

【讨论】:

    猜你喜欢
    • 2018-06-06
    • 2021-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多