3

I'm trying to figure out what is going on with my code and I can't figure it out. I'm trying to query a db to find out information where a user previously selected a variable.

The problem I'm running into is that it never replaces the @client with the value in the Parameters.AddWithValue method. I'm just not sure what I'm doing wrong.

selClient = comboBox1.SelectedItem.ToString();
string cmdText = "Select [Tax EIN] From [TblClientInfo] Where [Client Name] = '@client';";

using (var conn = new SqlConnection("connection info"))
{
    SqlCommand cmd2 = new SqlCommand(cmdText, conn);
    {
        cmd2.Parameters.AddWithValue("@client", selClient);
        try
        {
            conn.Open();
            SqlDataReader rd = cmd2.ExecuteReader();
            while (rd.Read())
            {
                MessageBox.Show(String.Format("{0}", rd[0]));
            }
            conn.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        finally
        {
            conn.Close();
        }
    }
}

Please ignore all of the generic variables, I'm new to programming and am trying to do this all as a test run before I actually make a usable program.

2 Answers 2

5

Remove the single quotes around the parameter in the sql string:

string cmdText = "Select [Tax EIN] From [TblClientInfo] Where [Client Name] = @client;";

While I'm here, I'm not a fan of .AddWithValue(), and there are a number of other improvements you can make as well:

selClient = comboBox1.SelectedItem.ToString();
string cmdText = "Select [Tax EIN] From [TblClientInfo] Where [Client Name] = @client;";

//whenever I see a "cmd2", I wonder about "cmd1"... 
//  that you probably can and should get this into a single call into the database
using (var conn = new SqlConnection("connection info"))
using (var cmd2 = new SqlCommand(cmdText, conn))
{
    //guessing a parameter type/length here. Use exact type from your DB.
    cmd2.Parameters.Add("@client", SqlDbType.NVarChar,50).Value = selClient;
    conn.Open();

    // I prefer my try/catch block to happen up at least one level
    // Code at that level is usually better positioned to react to the exceptions

    var rd = cmd2.ExecuteReader();
    while (rd.Read())
    {
        MessageBox.Show(rd[0].ToString());
    }
    //The main point of a using block with SqlConnection is that is safely closes the connection for you
}
Sign up to request clarification or add additional context in comments.

1 Comment

Remove quotes from the second example.
1

You must remove quotes '' from parameter @client :

string cmdText = "Select [Tax EIN] From [TblClientInfo] Where [Client Name] = @client;";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.