2014-07-12 84 views
0
SqlConnection cnn = new SqlConnection(); 

SqlCommand cmd = new SqlCommand(); 
cmd.CommandType = CommandType.Text; 
cmd.CommandText = "select * from [Test]"; 

cnn.Open(); 

SqlDataAdapter adp = new SqlDataAdapter(cmd); 
DataSet ds = new DataSet(); 

adp.Fill(ds); 

Choices sList = new Choices(); 

我想從我的數據庫中的表中填充sList從數據庫中填充選項

我該怎麼做?

回答

0

1)獲取您從Tables財產所需要的表:

var dataTable = ds.Tables["Test"]; 

2)創建將每個DataRow轉換爲類的實例的方法你需要在您的Choices列表中(本例中我稱之爲Choice):

Choice DataRowToChoice(DataRow row) 
{ 
    return new Choice() { Property1 = row["column1"] as string }; // ... etc. 
} 

您可以在文檔here中瞭解如何從DataRow中檢索數據。

3)通過行迭代:

foreach (var row in dataTable.Rows) 
{ 
    sList.Add(DataRowToChoice(row)); 
} 

Rows屬性的文檔可以發現here

0

也許這可以幫助

Choices sList = new Choices(); 
    foreach (DataRow dr in ds.Table[0].Rows) { 
    sList.Name = dr["name"]; // Or whatever your property is 
    }