0

I have a problem. I want to get data from my SQL Server database. When the code is running, the first row isn't getting added to my arraylist. All other rows get added successfully. In SQL Server, the query works fine, but in VS, it doesn't work.

private void button1_Click(object sender, EventArgs e)
{
    SqlConnection baglanti = new SqlConnection("server=.; Initial Catalog=TripData;Integrated Security=SSPI");
    baglanti.Open();

    SqlCommand komut = new SqlCommand();
    komut.CommandText = "select top 50 trip_ID from Sayfa1$";
    komut.Connection = baglanti;

    komut.ExecuteNonQuery();

    SqlDataReader oku = komut.ExecuteReader();

    while (oku.Read())
    {
        foreach (var item in oku)
        {
            gecici.Add(oku["trip_ID"].ToString());
        }
    }
}
2
  • You don't need foreach loop here. Just remove it and it should work fine Commented Apr 21, 2018 at 8:07
  • 2
    I would remove that ExecuteNonQuery() on the query. Commented Apr 21, 2018 at 8:39

1 Answer 1

4

You're trying to iterate over the reader in two different ways - using both a foreach loop and using while (reader.Read()). You should do one or the other - I've personally seen more code using while (reader.Read()) than the foreach approach.

Additionally I'd suggest using using statements for the disposable objects in your code - and not calling ExecuteNonQuery first. (It's not clear why you're doing that at all). So you could write:

// Note that this looks like a mixture of UI and non-UI code; consider separating
// them for greater code reuse, separation of concerns etc.
private void button1_Click(object sender, EventArgs e)
{
    // Declare connectionString elsewhere, or have a common method to open the connection.
    // You're likely to need that in multiple places.
    using (var connection = new SqlConnection(connectionString))
    {
        connection.Open();
        using (var command = new SqlCommand("select top 50 trip_ID from Sayfa1$", connection))
        {
            using (var reader = command.ExecuteReader())
            {    
                while (reader.Read())
                {
                    gecici.Add(oku["trip_ID"].ToString());
                }
            }
        }
    }
}

(Also if you're really using ArrayList as your post suggests, I'd definitely urge you to start using the generic collections, e.g. List<string> in this case.)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.