访问DataReader中的特定行
本文关键字:DataReader 访问 | 更新日期: 2023-09-27 18:04:18
我有一个数据阅读器显示一个列表的游戏周在js轮询器
我需要能够添加一个if语句来改变当前gameweek的div类。
这是我当前的代码:
if (dReader.HasRows) {
while (dReader.Read()) {
gameweekList.Text += "<div class='"item'"><h4>Gameweek " +
(dReader["gameweekID"].ToString()) + "</h4></div>";
}
} else {
gameweekList.Text = "Error Finding Gameweeks";
}
dReader.Close();
conn.Close();
实际上我想添加if(dreader[1])
,然后添加额外的位,这是怎么可能的?
我发现使用DataTable或DataSet更容易。像这样:
DataTable dt = new DataTable();
dt.Load(dreader)
那么您可以更容易地使用DataTable访问某一行。行属性。
…
if (dReader.HasRows) {
while (dReader.Read()) {
if ( dReader["gameweekID"].ToString() == currentWeekId )
{
gameweekList.Text += "<div class='"somethingSpecial'"><h4>Gameweek " +
(dReader["gameweekID"].ToString()) + "</h4></div>";
}
else
{
gameweekList.Text += "<div class='"item'"><h4>Gameweek " +
(dReader["gameweekID"].ToString()) + "</h4></div>";
}
}
} else {
gameweekList.Text = "Error Finding Gameweeks";
}
dReader.Close();
conn.Close();
如果我没记错的话,你可以像这样计算读者的阅读次数。然后,当计数适合您时,您可以添加一些不同的内容:
int count = 0;
if (dReader.HasRows) {
while (dReader.Read()) {
if(count == 1) //add special row
gameweekList.Text += "something special " + dReader["gameweekID"].ToString();
else
gameweekList.Text += "<div class='"item'"><h4>Gameweek " +
(dReader["gameweekID"].ToString()) + "</h4></div>";
count++;
}
} else {
gameweekList.Text = "Error Finding Gameweeks";
}
dReader.Close();
conn.Close();
但是如果你想同时读取当前和后续,你应该先读取一次,然后开始像这样循环读取:
if (dReader.HasRows) {
string previousRead = string.Empty;
dReader.Read();
previousRead = dReader["gameweekID"].ToString();
while (dReader.Read()) {
//use current and previous read
//dReader["gameweekID"].ToString()
//previousRead
//update previousRead for the next read
previousRead = dReader["gameweekID"].ToString();
}
} else {
gameweekList.Text = "Error Finding Gameweeks";
}
dReader.Close();
conn.Close();
要获得第一行,从0开始并始终将其放入数据表中,因为直接从数据阅读器读取总是会遇到问题;
if (dReader.HasRows) {
DataTable dt = new DataTable();
dt.Load(dreader)
gameweekList.Text = dt.Rows[0]["gameweekID"]
}