-1

I'm trying to read data from the data source and I got this error in the ExecuteReader method, When I try to show the result in some label.

I'm getting the error here idlabel.Text = myraeder("id"); under myreader varibale

private void Searchbtn_Click(object sender, EventArgs e)
{
   SqlConnection con = new SqlConnection(dataConnectin);
   con.Open();

   string searchsql = "SELECT * from Table WHERE Name=" + searchtxt.Text + "";
   SqlCommand cmd = new SqlCommand(searchsql, con);

   SqlDataReader myraeder;
   myraeder = cmd.ExecuteReader();
   myraeder.Read();

   idlabel.Text = myraeder("id");
}
3
  • What error do you get? Commented Aug 16, 2020 at 11:31
  • Use this one myraeder["id"].ToString(); Commented Aug 16, 2020 at 11:31
  • 1
    Be aware of the sql injection possibility here. Commented Aug 16, 2020 at 11:43

3 Answers 3

1
  1. Use square brackets instead of round brackets.
  2. Convert the field to string.
    idlabel.Text = myraeder["id"].ToString();
Sign up to request clarification or add additional context in comments.

Comments

1

Read the data in this way:

idlabel.Text = myraeder["id"].ToString();
con.Close();

And do not forget to close the connection after getting required data.

1 Comment

Is it worked for you and your issue is resolved ?
1

There are so many errors that are obvious. Let me show you a better way to write code. Follow me!

  • Give the variables proper names and casing.
  • Use asynchrony.
  • Use parameters in sql queries.
  • Release resources by wrapping them in using.
  • Enclose names in brackets in sql.
private async void SearchButton_Click(object sender, EventArgs e)
{
    using (var connection = new SqlConnection(connectionString))
    {
        await connection.OpenAsync();

        string searchSql = "SELECT * from [Table] WHERE [Name]=@name";

        using (var command = new SqlCommand(searchSql, connection))
        {
            command.Parameters.Add("name", SqlDbType.NVarChar).Value = searchTextBox.Text;

            using (var reader = await command.ExecuteReaderAsync())
            {
                while (await reader.ReadAsync())
                {
                    idLabel.Text = reader["id"].ToString();
                }
            }
        }
    }
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.