开发者

immediate fetching of data from sql database from winforms textbox

I am using Winforms for my application & SQL Server as database.

I want that as soon as any text is typed in a textbox , immediate results are fetched/searched from the SQL SERVER database tables for that supplied text.

For this , i have given the following query:

    public partial class Form1 : Form
{
    SqlConnection conn = new SqlConnection();
    public Form1()
    {
        conn.ConnectionString = "Trusted_Connect开发者_如何学Cion=true";
        conn.Open();
        InitializeComponent();
    }

    private void textBox1_TextChanged(object sender, EventArgs e)
    {

        DataTable dt = null;

        SqlCommand cmd = new SqlCommand ("SELECT * FROM items WHERE item_name LIKE'" +    textBox1.Text + "%'", conn);
        SqlDataReader reader = cmd.ExecuteReader();

        dt = new DataTable();

        dt.Load(reader);

        dataGridView1.DataSource = dt;

    }
}

But , as this fetches data every time from the database, so it takes more time, but i want a faster way. so shall i use DATASETS for this purpose, as datasets are used for disconnected environment.

OR

I shall first fetch the whole ITEM table from the database on to a GridView , & display it when the Form is opened.

now, when text is entered in the textbox , then it would not fetch data from the sql database, but would search in the GridView, so would this be faster?

which way would be efficient?

The item table has 3.4 million records.


How big is your items table?

If it's not big, it'll do to just store it in a dataset. Use the same textbox but search in the dataset.

If it's big, I would suggest using a timer. On each textchange, restart the timer of maybe 0.5 seconds. when the timer has elapsed, then only query the database. This prevents multiple queries while the user is typing.

Alternatively, if you could read the whole table and assign it to the AutoCompleteCustomSource:

textBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
foreach(DataRow row in dt.Rows)
    textBox1.AutoCompleteCustomSource.Add(row["item_name"] as string);


Yes. Using a dataset and searching on it would be much faster. Since you are using WinForms, memory footprint is probably also not an issue unless you you are fetching a huge number of rows from the database.

Also, you should probably not search on every text change, but wait for a small amount of time say 2 seconds during which there are no changes to the textbox and then fetch. Otherwise you would be fetching for any new character entered in the textbox (i think).


Better approach will be using DataSet / DataTable. Read all the data from the Table on the form load and store it in the Form.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜