-1

I would like to get data from my database to my label.

This is my code:

con = new SqlConnection(conS);

try
{
    con.Open();
    string q = "SELECT SearchTerm FROM Sentiment WHERE Sentiment = 'positive'";

    SqlCommand query = new SqlCommand(q, con);

    using (SqlDataReader dr = query.ExecuteReader())
    {
        bool success = dr.Read();

        if (success)
        {
            // Label1.Text = dr.GetString(1);
            label3.Text = dr.GetString(1);
        }
    }

    con.Close();
}
catch (Exception ex)
{
    label3.Text = "Error";
}

However when I run the application, my label is showing 'Error'. What is wrong with this code?

Thank you in advance :)

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Fairuz
  • 11
  • 3
  • You are getting an `exception`, debug your code. – Arghya C Dec 28 '15 at 04:54
  • Did you tried to debug and see what is the exception ? Can you elaborate on the connection string? – Venkatesh Dec 28 '15 at 04:54
  • 2
    First, dont show `label3.Text = "Error";` in your exception. it's not informative. You can use `label3.Text = ex.Message;` to get a detail ed error. Second one, make sure the query is returning only 1 record. try to change the code to `SELECT TOP 1 SearchTerm FROM Sentiment WHERE Sentiment = 'positive'` – vantian Dec 28 '15 at 04:55
  • when debugged, it says index was outside the bounds of the array. What does this means? – Fairuz Dec 28 '15 at 05:01
  • 3
    try 'label3.Text = dr.GetString(0);' – Quantumplate Dec 28 '15 at 05:02

1 Answers1

1

Try to Get Top 1 record using select query.

 string q = "SELECT TOP 1 SearchTerm FROM Sentiment WHERE Sentiment = 'positive'";

and

label3.Text = dr.GetString(0);

Hope it will help.

Ghasem
  • 14,455
  • 21
  • 138
  • 171
HirenPatel
  • 204
  • 2
  • 8