Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 all times! how can i read all of reader information with a while or repeater ring?

like image 503
Mahdi_Nine Avatar asked Dec 07 '25 06:12

Mahdi_Nine


2 Answers

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

while (reader.Read())
{
     // grab data
}
like image 154
Anthony Pegram Avatar answered Dec 09 '25 00:12

Anthony Pegram


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();
like image 42
p.campbell Avatar answered Dec 09 '25 00:12

p.campbell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!