Muzamil Abbas
Muzamil Abbas

Reputation: 702

Search By Name in c#

I have the Follwing Code. To search by StdName but when i run this code it shows empty cells in datagrid view. Help me to correct this.

 private void btnSBN_Click(object sender, EventArgs e)
    {
        String query = "Select * from Student where StdName like '*@Name*'";

        OleDbCommand cmd = new OleDbCommand(query, cn);
        cmd.Parameters.Add("@Name", OleDbType.VarChar, 20);
        cmd.Parameters["@Name"].Value = txtName.Text;
        OleDbDataAdapter da = new OleDbDataAdapter();
        da.SelectCommand = cmd;

        try
        {
            DataSet ds = new DataSet();
            da.Fill(ds,"SBN");
            dgStudent.DataSource = ds;
            dgStudent.DataMember = "SBN";
            dgStudent.Refresh();
        }
        catch (OleDbException ex)
        {
            MessageBox.Show(ex.Message);
        }


    }

Compiler shows no syntax error and no exceptions. but show empty cells in datagrid view.

Upvotes: 0

Views: 2391

Answers (2)

Gord Thompson
Gord Thompson

Reputation: 123799

When working with parameter queries remember that you should never have delimiters in the CommandText. If delimiters are required in the background the OleDbCommand object will take care of them for you.

String query = "Select * from Student where StdName like @Name";
OleDbCommand cmd = new OleDbCommand(query, cn);
cmd.Parameters.Add("@Name", OleDbType.VarChar, 20);
cmd.Parameters["@Name"].Value = "%" + txtName.Text + "%";

Upvotes: 0

Jon
Jon

Reputation: 121

'*@Name*'

is your problem.

If you're looking for an exact match, don't have the '*'s.

If you're looking for an instance where the @Name is found somewhere in the StdName, use:

'%' + @Name + '%'.

You also shouldn't have @Name inside the quotes. If it's an exact match:

StdName = @Name

Upvotes: 2

Related Questions