2009-09-23 47 views
1

如何爲數組指定數據庫值。我想是這樣的...如何爲陣列指定值

da = new SqlDataAdapter("select emname from emp", con); 
     ds = new DataSet(); 
     da.Fill(ds, "emp"); 
     if(ds.Tables [0].Rows.Count >0) 
     { 
      for(int i=0;i<ds.Tables [0].Rows .Count ;i++) 
      { 
       string[] myArray = ds.Tables[0].Rows[i]["emname"].ToString(); 
      } 
     } 

,但它給能串不能轉換爲字符串錯誤[] 請幫我

回答

5

試試這個:

da = new SqlDataAdapter("select emname from emp", con); 
ds = new DataSet(); 
da.Fill(ds, "emp"); 
if(ds.Tables[0].Rows.Count > 0) 
{ 
    string[] myArray = new string[ds.Tables[0].Rows.Count]; 
    for (int i = 0; i < ds.Tables[0].Rows.Count; i++) 
    { 
     myArray[i] = ds.Tables[0].Rows[i]["emname"].ToString(); 
    } 
    // Use myArray here... 
} 

注意,有是使用LINQ做這件事的更好方法,但如果您對C#/ .NET很陌生,我建議您在深入LINQ之前熟悉基本知識。

+0

@ surya-如果你決定來看看LINQ,你會想看看LINQ to DataSet - http://msdn.microsoft.com/en-us/library/bb386977.aspx – RichardOD 2009-09-23 08:11:22

+0

謝謝你能告訴我哪本書可以參考 – 2009-09-23 08:11:57

+1

LINQ in Action(Fabrice Marguerie,Steve Eichert,和Jim Wooley)和Pro LINQ(Joe Rattz)都很好。我也聽說過關於Essential LINQ(Charlie Calvert和Dinesh Kulkarni)的好消息,但我還沒有讀過它。 – 2009-09-23 08:13:44

0

您試圖在每個循環中初始化一個新數組,並且最重要的是,您還試圖將其分配爲字符串而不是數組。

string [] [] myArray = ds.Tables [0] .Rows將是正確的解決方案。另請注意,行是一個多維數組。如果你想要一個填充了特定行的數組,你也可以使用string [] myArray = dt.Tables [0] .Rows [0]。

0

如果你希望所有的名稱的數組,你可以轉換的DataRow一個數組的string數組這樣的:

da = new SqlDataAdapter("select emname from emp", con); 
ds = new DataSet(); 
da.Fill(ds, "emp"); 
string[] myArray = Array.ConvertAll<DataRow, string>(ds.Tables[0].Select(), 
         delegate(DataRow row) { return row["emname"].ToString(); });