2012-02-09 17 views
5

Tôi có truy vấn sql trong ứng dụng web asp.net của tôi và kết quả được lưu trữ trong bộ dữ liệu. Mỗi hàng trong bộ dữ liệu chứa 10 cột. Tôi muốn điền vào bảng với những dữ liệu này. Tuy nhiên, tôi không có ý tưởng, làm thế nào để lặp qua các cột trong datareader. Tôi cần một cái gì đó như thế này:asp.net sql datareader loop theo cột

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); 
    } 
} 

Tôi hy vọng bạn có điểm. Cảm ơn

Trả lời

14

Sử dụng FieldCount tài sản của SqlDataReader:

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

cảm ơn, đó chính xác là những gì tôi cần – polohy

1

Bạn chỉ nên làm điều đó thông qua một 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); 

Tại thời điểm này, bạn DataTable (dt) chứa tất cả các dữ liệu từ truy vấn của bạn.

+1

Có vẻ như bảng ASP của nó không phải là một DataTable – Magnus

+0

, tôi cũng sẽ thử nó quá – polohy

+0

@Magnus ASP table? Tôi không đi theo. Đó chắc chắn là một 'DataTable' với dữ liệu hoàn chỉnh từ truy vấn của' SqlCommand'. –