user3124727
user3124727

Reputation: 11

fetch data into datagridview from textbox's selected text

In textbox I am fetching city name and when I select any city name, information related to that city should display on datagridview, to fetch other information about the state I used a foreign key because state table is different and its information is stored in another table so I fetch that information from foreign key state_id. Here is my code

DataTable dt = new DataTable();
SqlDataAdapter tda = new SqlDataAdapter("SELECT a1.type,a1.state_id,a1.desc1,a1.from_date,a1.to_date,a1.expr1005 FROM item_rate a1 FULL OUTER JOIN item_rate_state a2 ON a1.state_id=a2.state_id WHERE state_name='" + textBox2.Text + "'", scon);
            tda.Fill(dt);
            dataGridView2.DataSource = dt;

Upvotes: 1

Views: 218

Answers (2)

Parimal Raj
Parimal Raj

Reputation: 20585

The query seems a little wrong

it should be

SqlDataAdapter tda = new SqlDataAdapter("SELECT a1.type,a1.state_id,a1.desc1,a1.from_date,a1.to_date,a1.expr1005 FROM item_rate a1 FULL OUTER JOIN item_rate_state a2 ON a1.state_id=a2.state_id WHERE a2.state_name='" + textBox2.Text + "'", scon);

i would suggest you to use SqlCommand and add parameters to query proper way as your code is vulnerable to sql injection!


Answer as per the comment.

since you do now want to show any record when textbox is empty simple on TextChanged event do this

if (!String.IsNotNullOrEmpty(textBox2.Text))
{

    DataTable dt = new DataTable();
    SqlDataAdapter tda = new SqlDataAdapter("SELECT a1.type,a1.state_id,a1.desc1,a1.from_date,a1.to_date,a1.expr1005 FROM item_rate a1 FULL OUTER JOIN item_rate_state a2 ON a1.state_id=a2.state_id WHERE a2.state_name='" + textBox2.Text + "'", scon);
    tda.Fill(dt);
    dataGridView2.DataSource = dt;

}

Upvotes: 1

Vignesh Kumar A
Vignesh Kumar A

Reputation: 28413

You have Try like this

Set textBox2.AutoPostBack="True" in design page

 protected void textBox2_TextChanged(object sender, EventArgs e)
    {
DataTable dt = new DataTable();
SqlDataAdapter tda = new SqlDataAdapter("SELECT a1.type,a1.state_id,a1.desc1,a1.from_date,a1.to_date,a1.expr1005 FROM item_rate a1 FULL OUTER JOIN item_rate_state a2 ON a1.state_id=a2.state_id WHERE state_name='" + textBox2.Text + "'", scon);
            tda.Fill(dt);
            dataGridView2.DataSource = dt;
    }

Upvotes: 0

Related Questions