Austin
Austin

Reputation: 75

How to get the top row in C# of a stored procedure?

I just need the top row, the stored procedure uses TOP 1, but I would like to have it in the C# to future proof this app a little.

        protected void Load()
        {
            using (SqlConnection objConn = new SqlConnection(ConfigurationManager.AppSettings["Connection"]))
            using (SqlCommand com = new SqlCommand("StoredProcedure", objConn))
            {
                objConn.Open();
                com.CommandType = CommandType.StoredProcedure;

                using (SqlDataReader dr = com.ExecuteReader())
                {
                    while (dr.Read())
                    {
                        txtLabel.Text = dr["label"].ToString();
                        txtLabel.Text = dr["label"].ToString();
                        txtLabel.Text = dr["label"].ToString();
                    }
                }
            }
        }

Upvotes: 0

Views: 362

Answers (1)

Neil
Neil

Reputation: 11889

Get rid of the loop while(dr.Read()):

    protected void Load()
    {
        using (SqlConnection objConn = new SqlConnection(ConfigurationManager.AppSettings["Connection"]))
        using (SqlCommand com = new SqlCommand("StoredProcedure", objConn))
        {
            objConn.Open();
            com.CommandType = CommandType.StoredProcedure;

            using (SqlDataReader dr = com.ExecuteReader())
            {
                if(dr.HasRows && dr.Read()) // <----- This is the change
                {
                    txtLabel.Text = dr["label"].ToString();
                    txtLabel.Text = dr["label"].ToString();
                    txtLabel.Text = dr["label"].ToString();
                }
            }
        }
    }

Upvotes: 3

Related Questions