2012-02-09 59 views
5

我在我的asp.net webapp中有sql查詢,結果存儲在datareader中。數據記錄器中的每一行都包含10列。我想用這些數據填充表格。但是,我不知道如何循環訪問數據記錄器中的列。我需要像這樣的東西:asp.net sql datareader按列循環

while (vysledky.Read()) 
{ 
    TableRow row = new TableRow(); 
    tab.Controls.Add(row); 
    foreach (column in ((datareader(row))) //it is not real code 
    { 
     TableCell cell = new TableCell(); 
     cell.Text = datareader(row).content; 
     row.Controls.Add(cell); 
    } 
} 

我希望你明白了。由於

回答

14

使用SqlDataReaderFieldCount屬性:

while (vysledky.Read()) 
{ 
    // Iterate over each of the fields (columns) in the datareader's current record 
    for (int i = 0; i < vysledky.FieldCount; i++) 
    { 
     var value = vysledky[i]; 

     TableCell cell = new TableCell(); 
     cell.Text = Convert.ToString(value); 
     row.Controls.Add(cell); 
    } 
} 
+0

謝謝,這正是我所需要的 – polohy 2012-02-09 17:59:43

1

你應該做它通過SqlDataAdapter

SqlConnection Conn = new SqlConnection(YourConnectionString); 
SqlCommand YourSqlCommand = new SqlCommand(); 
YourSqlCommand.Connection = Conn; 
YourSqlCommand.CommandText = "select * from yourtable"; 

DataTable dt = new DataTable(); 

SqlDataAdapter sda = new SqlDataAdapter(YourSqlCommand); 

sda.Fill(dt); 

在點,你DataTabledt)中包含的所有數據從您的查詢。

+1

看起來像它的ASP表不是一個DataTable – Magnus 2012-02-09 18:01:20

+0

不錯,我也會試試 – polohy 2012-02-09 18:01:52

+0

@Magnus ASP表?我沒有跟隨。這絕對是一個'DataTable',具有來自'SqlCommand'查詢的完整數據。 – 2012-02-09 18:10:29