开发者

how can i know when i reach end of a datareader?

cmd.CommandText = "select name from Tbl_Shahr_No";
SqlDataReader reader = null;
reader = cmd.ExecuteReader();
reader.Read();

while(reader.HasRows)
{
    ddl.Items.add(reader["name"].tostring());
    reader.read()
}

i wrote this code but problem is that while statement is true a开发者_Go百科ll times! how can i read all of reader information with a while or repeater ring?


The simplest idea is to simply let Read() be the loop condition.

while (reader.Read())
{
     // grab data
}


Use the .Read() method in your while.

It advances the SqlDataReader to the next record.

Returns true if there are more rows; otherwise false.

while(reader.Read())
{
   ddl.Items.add(reader["name"].ToString());
}

Alternatively, data-bind your dropdownlist to your SqlDataReader, and don't bother iterating it manually.

ddl.DataSource = reader;
ddl.DataTextField = "name";
ddl.DataValueField = "name";
ddl.DataBind();


When reader.Read() returns false then there are no more rows so by using

while(reader.Read())
{
    //do some thing here
}

it will loop until there are no more rows!

But if the datareader has more then one dataset use the following

while(reader.Read())
{
    //First dataset
    //do some thing here
}
reader.NextResult();
while(reader.Read())
{
    //Second dataset
    //do some thing here
}
......


IDataReader.Read() returns a bool. Use it as the condition for your while-loop:

reader = cmd.ExecuteReader();            
while(reader.Read())
{
    ddl.Items.add(reader["name"].tostring());
}


while (reader.read())
{
   // do your thing here for each row read
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜