【问题标题】:how to use multidimensional array using C#如何使用 C# 使用多维数组
【发布时间】:2015-06-19 16:10:31
【问题描述】:

如何将多个列值读入数组列表?我正在尝试将数据库中的类别名称和类别 ID 列表读取到数组列表中;然后我将这些值绑定到下拉列表中。使用我当前的代码,我只能处理一列,但想同时提取 cat_name 和 cat_id 那我该怎么做?

 <asp:DropDownList ID="DropDownList1" runat="server"  DataTextField="ct_name" DataValueField="ct_id" AppendDataBoundItems="true">
            <asp:ListItem Value="-1">Select</asp:ListItem>
            </asp:DropDownList>

下面是代码

 private ArrayList GetDummyData()
 {
     ArrayList arr = new ArrayList();
     string strConn = ConfigurationManager.ConnectionStrings["myCon"].ConnectionString.ToString();
     SqlConnection con = new SqlConnection(strConn);
     con.Open();
     SqlCommand cmd = new SqlCommand("select distinct ct_name, cat_id from [myTable].[dbo].[categories]", con);
     SqlDataReader objDR = cmd.ExecuteReader();

     if (objDR != null) {
         while (objDR.Read())
         {
             //fill arraylist
             arr.Add(objDR["ct_name"]);
         }
     }

     con.Close();
     return arr;
 }

 private void FillDropDownList(DropDownList ddl)
 {
     ArrayList arr = GetDummyData();
     foreach (string item in arr)
     {
         ddl.Items.Add(item);
     }
}    

【问题讨论】:

  • 也许你应该使用 Dictionary, dic.Add(Convert.ToInt32(objDR["cat_id"]),objDR["ct_name"])
  • 旁注:在大多数情况下,最好不要使用多维数组(如int[10,10])......而且看起来你甚至没有单个数组 - ArrayList 不是“数组”并且通常已过时(改用List&lt;T&gt;)。
  • 为什么不替换使用阅读器,只返回一个DataTable?您可以将 Rows 绑定到 DropDownList。您的 DataTexField 和 DataValueField 已正确设置。否则你应该做 ddl.Items.Add(new ListItem(objDR["ct_name"], objDR["ct_id"]));不需要临时的对象列表。
  • 谢谢 Dacker,你能给我看看这个例子吗?

标签: c# asp.net arrays multidimensional-array


【解决方案1】:

使用“多维数组”的最佳方式通常是不使用一个,而是使用强类型数据:

class Category
{
  public string Name {get;set;}
  public string Id {get;set;}
}

List<Category> categories = new List<Category>();
while (objDR.Read())
{
    categories.Add(new Category { 
       Name = objDR["ct_name"],
       Id =  objDR["ct_id"],
    };
}

【讨论】:

    【解决方案2】:

    如果您尝试将两个项目并排放在下拉列表中,那么您可以使用

    SELECT concat(cat_id," ", ct_name) ...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-03
      • 1970-01-01
      • 1970-01-01
      • 2023-04-10
      • 1970-01-01
      • 1970-01-01
      • 2014-01-18
      • 1970-01-01
      相关资源
      最近更新 更多