c# - 根据数据库值预选列表框中的多个项目

标签 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();
            }
        }
    }
}

最佳答案

您必须循环所有项目并相应地设置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 将转换为 SqlDbTypedifferent 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 specify integer parameter values. Because this overload takes a value of type Object, 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/

相关文章:

c# - .NET WinForms 中 UI 元素的授权

jquery - 在我的网页上显示动态数据(进度)

c# - 将观察者集合分配给列表框时出错

.net - WPF ListBox VirtualizingStackPanel.VirtualizationMode ="Recycling"导致相同的列表项始终出现

c# - 将 Windows 窗体对象添加到列表框

c# - UpdatePanel 中 UpdateMethod 后 GridView 的刷新

c# - UWP XAML 模板化控件 - "Edit a Copy"已禁用

c# - 我们在 MS-Access 中有交易吗?

c# - 由 ASP.NET Web 应用程序设置的 Cookie 有多安全?

c# - 如何避免 Controller 中每个 Action 发生的重复代码