Skip to main content
 首页 » 编程设计

c#之如何使用C#使用多维数组

2024年02月06日11zlslch

如何将多个列值读入数组列表?我正在尝试从数据库中读取类别名称和类别 ID 的列表到数组列表中;然后我将这些值绑定(bind)到下拉列表中。使用我当前的代码,我只能处理一列,但我想同时提取 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); 
     } 
}     

请您参考如下方法:

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

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"], 
    }; 
}