Pregunta

I have a search textbox in my windows form application and I want to search character by character means when I write h in textbox then shows result in datagridview of h and when I add h with a like ha in search textbox then shows result in datagridview of ha and its change results in datagridview from h to ha as same as mobile phone contacts searching. and I working like below:

public partial class Form2 : Form
{
    SqlConnection connection = new SqlConnection("Data Source=(LocalDB)\\v11.0;AttachDbFilename=C:\\Users\\Administrator\\Documents\\Contact.mdf;Integrated Security=True;");
    SqlDataAdapter da = new SqlDataAdapter();
    DataSet ds = new DataSet();
    public Form2()
    {
        InitializeComponent();            
    }

    private void Form2_Load(object sender, EventArgs e)
    {
        bindDatagridview();  
        if (textBox1.Text != string.Empty)      
        {      
            search();            
        }
    }
    public void bindDatagridview()
    {
        SqlDataAdapter da = new SqlDataAdapter();
        DataSet ds = new DataSet();
        da.SelectCommand = new SqlCommand("Select * from contactsinfo", connection);
        da.Fill(ds);
        dataGridView1.DataSource = ds.Tables[0];
        //dataGridView1.DataBindings();
    }
    public void search()
    {
        da.SelectCommand = new SqlCommand("Select * from contactsinfo where ContactName = '" + textBox1.Text + "'", connection);
        da.Fill(ds);
        dataGridView1.DataSource = ds.Tables[0];
        clear();
    }
}

But this only work when the form is load and the form is only loaded at first time: Kindly suggest me what i do, waiting for your reply. Thanks.

¿Fue útil?

Solución

If you can load all contacts at once, then its simple. On form load get all contacts and save them in DataView. Then bind grid to this view:

DataView contactsView;

private void Form2_Load(object sender, EventArgs e)
{
    DataTable dt = new DataTable();
    using (SqlConnection conn = new SqlConnection(connectionString))
    {
        var da = new SqlDataAdapter("SELECT * FROM from contactsinfo", conn);
        da.Fill(dt);
    }

    contactsView = dt.AsDataView();
    dataGridView1.DataSource = contactsView;    
}

Then just change row filter of DataView when text changes in filter TextBox:

private void textBox1_TextChanged(object sender, EventArgs e)
{
    contactsView.RowFilter = 
       String.Format("ContactName LIKE '{0}%'", textBox1.Text);
}

If you can't pre-load all data, then you should use same TextChanged event to query for filtered data.

NOTE: You should handle ' in user input.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top