2009-10-15 28 views
0

我有一個表中的5個名字,我需要把這些放在一個數組列表中....將表中的名稱放入arraylist中?

任何建議???

  int rowsinmachgrp = getnumofrows();//gets no of rows in table 

      SqlConnection dataConnection = new SqlConnection(); 
      dataConnection.ConnectionString = ConfigurationManager.ConnectionStrings["SumooHAgentDBConnectionString"].ConnectionString; 
      SqlCommand dataCommand = 
        new SqlCommand("select MachineGroupName from MachineGroups", dataConnection); 

      {ArrayList names = new ArrayList(); 
       dataConnection.Open(); 
       ArrayList names = dataCommand.ExecuteScalar(); 

感謝

回答

5

這是你的:

List<string> names = new List<string>(); 
using(SqlConnection db = new SqlConnection(ConfigurationManager...)) 
{ 
    db.Open(); 
    SqlCommand cmd = new SqlCommand("Select ....", db); 

    using(SqlDataReader rd = cmd.ExecuteReader()) 
    { 
     while(rd.Read()) 
     { 
      names.Add(rd.GetString(0)); 
     } 
    } 
} 

未經測試!

+0

您正在將名稱添加到列表的行中缺少右括號。 – 2009-10-15 15:13:13

+0

THX!修復。我不知道該說些什麼才能得到15個字符的評論 – Arthur 2009-10-15 15:17:11

+0

SQLdataread找不到......錯誤.. dataread的使用命令是什麼.. ?? – user175084 2009-10-15 15:24:46

0

更正代碼:

ArrayList names = new ArrayList(); 

int rowsinmachgrp = getnumofrows();//gets no of rows in table 

SqlConnection dataConnection = new SqlConnection(); 
dataConnection.ConnectionString = ConfigurationManager.ConnectionStrings["SumooHAgentDBConnectionString"].ConnectionString; 
SqlCommand dataCommand = new SqlCommand("select MachineGroupName from MachineGroups", dataConnection); 


    dataConnection.Open(); 
    SqlDataReader rdr = dataCommand.ExecuteReader(); 
    while (rdr.Read()) 
    { 
    names.Add(rdr.GetString(0)); 
    } 
dataCommand.Dispose(); 
dataConnection.Dispose(); 

請注意,而我解決您的直接問題,你有事情很多其他的問題,比如你的rowsinmachgrp變量,使用ArrayList,而不是使用using :)

相關問題