[英]asp.net sql datareader loop by columns
我的asp.net webapp中有sql查詢,結果存儲在datareader中。 datareader中的每一行包含10列。 我想用這些數據填充表格。 但是,我不知道如何遍歷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);
}
}
我希望你明白這一點。 謝謝
使用SqlDataReader
的FieldCount
屬性:
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);
}
}
你應該通過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);
此時,您的DataTable
( dt
)包含查詢中的所有數據。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.