2014-09-23 82 views
3

我有一个列表框,在加载页面时,我想要选择数据库中的选项/选项。我已经用列表框做了一段时间,所以我对如何修正我的GetClassification函数的代码有点困惑,它意味着要做到这一点。目前,它仅在列表框中选择一个值,而不管该厂商ID是否与多个关联。基于数据库值预先选择列表框中的多个项目

这是GetClassification函数的代码:你要循环的所有项目,并设置Selected,物业因此

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(); 
      } 
     } 
    } 
} 
+0

你不需要'@ ClassId'因为你没有申报在'SqlCommand'此参数。 – 2014-09-23 12:47:30

+0

ASP.NET是我正在使用的。 – 2014-09-23 12:50:23

回答

2

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

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)); 
+0

上述唯一的问题是,对于while循环内的行,我看到这个错误:System.Data.IDataRecord.GetString(int)的最佳过载匹配有一些无效的参数... – 2014-09-23 12:58:14

+0

@ gallifrey1212:then它实际上是一个'int'。我更喜欢'Get ...'方法,因为如果我错误地使用了错误的数据类型,并且我没有得到隐式转换(比如'DateTime',包括本地化问题),它们会失败。请注意,我已经添加了我的答案。 – 2014-09-23 13:00:11

+0

好吧,我应用了这些变化,它完美的工作。非常感谢 :) – 2014-09-23 13:05:41

0

检查ListBox的SelectionMode属性是否以多个选项的形式给出,这将启用多项选择。

e.g

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