Mert Metin
Mert Metin

Reputation: 411

else statement of Datatable

string sql = "select * from customer where name like '" + textBox2.Text + "%'";
string sql2 = "select * from customer";

if (textBox2.Text.Length > 0)
{
    DataTable dt = CarDatabase.executeSelect(sql);
    DataTable dt2 = CarDatabase.executeSelect(sql2);

    if (dt == null)
    {
        dataGridView2.DataSource = dt2;
        MessageBox.Show("There's no result with " + textBox2.Text);
    }
    else if (dt != null)
        dataGridView2.DataSource = dt;
}
else
{
    MessageBox.Show("Please fill the textbox");
}

I try to do "if like has some result, show it in DataGrid". There's no problem with that. However, when like finds nothing in the database, the DataGrid stays old. However, if after searching there is no result, the DataGrid is empty.

Upvotes: 0

Views: 313

Answers (3)

Royi Namir
Royi Namir

Reputation: 148644

string sql = "select * from customer where name like '" + textBox2.Text + "%'";
string sql2 = "select * from customer";

if (textBox2.Text.Length > 0)
{
    DataTable dt = CarDatabase.executeSelect(sql);
    DataTable dt2 = CarDatabase.executeSelect(sql2);

    if (dt == null)
    {
        dataGridView2.DataSource = dt2;
        dataGridView2.DataBind();
        MessageBox.Show("There's no result with " + textBox2.Text);
    }
    else if (dt != null)
    {
        dataGridView2.DataSource = dt;
        dataGridView2.DataBind();
    }
}
else
{
    MessageBox.Show("Please fill the textbox");
}

Upvotes: 1

subodh
subodh

Reputation: 6158

You must have to use DataBind()

do the below line in your if else block as

dataGridView2.DataBind();

Updated:

           if (dt == null)
            {
                DataTable table = new DataTable();
                dataGridView2.DataSource = table ;
                MessageBox.Show("There's no result with " + textBox2.Text);
            }

Upvotes: 0

Amit Rai Sharma
Amit Rai Sharma

Reputation: 4225

Well it is a good practice to use a stored procedure than injecting sql query from the code.

I would have created a procedure something like this...

Create Procedure GetCustomers(@name varchar(100))
AS 
BEGIN
 select * from customer  where Name like (ISNULL(@name,Name))
END

However while passing value to the @name parameter, you need to append '%' to it. If textbox value is empty then pass null to @name. This query will return all customer if textbox value is empty else the requested customers.

Upvotes: 1

Related Questions