Hani Honey
Hani Honey

Reputation: 2131

Store SQL field as a variable?

I'm trying to select some fields from my database and store them as a variable so I can use them to display data on my page. So far I have this:

  protected void DefaultGrid_SelectedIndexChanged(Object sender, EventArgs e)
    {
        string firstName;
        GridViewRow row = DefaultGrid.SelectedRow;
        int id = Convert.ToInt32(row.Cells[9].Text);
        string checkStatement = "Return fName FROM SecureOrders WHERE IdentityColumn LIKE @identity";
        using (SqlConnection connection = new SqlConnection(connectionString.ToString()))
        using (SqlCommand _check = new SqlCommand(checkStatement, connection))
        {
            _check.Parameters.Add("@identity", SqlDbType.Int).Value = id;
            connection.Open();
            _check.ExecuteNonQuery();
            connection.Close();
        }

I'm wondering how I should alter this so that I can save the field fName in the variable called firstName. Am I on the right track?

Upvotes: 0

Views: 215

Answers (3)

Precious Roy
Precious Roy

Reputation: 1086

You're on the right track, but as far as how you plan to save the field should be determined by what you want to do with it once you've retrieved it. Are you going to display it? What are you going to display it in? Here's some basic syntax for a few scenarios. If you want more a more explicit answer, give a little more detail in your question.

Upvotes: 0

Brian
Brian

Reputation: 1894

If you're only returning 1 row and 1 field. You should use ExecuteScalar.

If you're going to return more than that, use a DataReader and ExecuteReader.

You should also place your connection within a using statement like your command. Your sql statememnt should be Select Field1, Field2..n from Table where X=@Variable

Upvotes: 0

SLaks
SLaks

Reputation: 887275

You can write firstName = (string) _check.ExecuteScalar()

Upvotes: 1

Related Questions