访问DataReader中的特定行

时间:2013-03-16 14:06:19

标签: c# asp.net sqldatareader datareader

我有一个datareader来显示js轮播中的游戏周列表。

我需要添加一个if语句来更改当前游戏周的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])然后添加额外的位,这怎么可能?

4 个答案:

答案 0 :(得分:7)

我发现使用DataTable或DataSet更容易。像这样:

DataTable dt = new DataTable();
dt.Load(dreader)

然后,您可以使用DataTable.Rows属性更轻松地到达某一行。

答案 1 :(得分:3)

如果我找到你的话,你可以算一下读者这样读。然后当计数适合你时,你可以添加不同的东西:

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

答案 2 :(得分:3)

怎么样......

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

答案 3 :(得分:0)

要获得第一行,请从0开始并始终将其放入数据表中,因为直接从数据读取器读取时总会遇到问题;

if (dReader.HasRows) {

DataTable dt = new DataTable();
dt.Load(dreader)
gameweekList.Text = dt.Rows[0]["gameweekID"]

}