Search by name in spreadsheet C#?

Asked

Viewed 40 times

-1

I am trying to do a name search inside an Excel spreadsheet, by code works normal, but I would like to search by name, when I do the search with the abix code, returns the error:

erro que ocorre

private void button2_Click(object sender, EventArgs e)
{
    try
    {
       _oleCmd.CommandText = "SELECT Nome FROM [Designa$] Where Nome=" + textBox1.Text;
       OleDbDataReader reader = _oleCmd.ExecuteReader();
       while (reader.Read())
       {
        textBox2.Text = reader.GetString(1);
       }
       reader.Close();
    }
    catch (Exception ex)
    {
       MessageBox.Show(ex.Message,this.Text,MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}
  • Apart from the lack of quotes you need to "escape" the value passed to query.

1 answer

2


You forgot the quotes (') time to look for the string name. This should work:

_oleCmd.CommandText = "SELECT Nome FROM [Designa$] Where Nome='" + textBox1.Text + "'";

Or

_oleCmd.CommandText = $"SELECT Nome FROM [Designa$] Where Nome='{textBox1.Text}'";
  • 1

    Both worked!! I just had to change the array to 0. Thanks, thanks!!

  • The two are the same thing written in different ways. In the second example string interpolation is used, you can see more about it here: https://docs.microsoft.com/pt-br/dotnet/csharp/language-reference/tokens/interpolated

Browser other questions tagged

You are not signed in. Login or sign up in order to post.