2

i have 2 text boxes. the problem which i am facing is that when i enter a number in textbox1, the program should fetch the data from database and display the result in textbox2 but with out the use of any button. i have no idea which event to use. here is a code but i guess it is useless:

private void textBox2_Click(object sender, EventArgs e)
{
    con.Open();
    cmd.Connection = con;
    cmd.CommandText = "SELECT item_name FROM prod_info WHERE barcode=" + textBox2.Text + "";
    cmd.ExecuteNonQuery();
    con.Close();
}
abatishchev
  • 98,240
  • 88
  • 296
  • 433
Haider Khattak
  • 567
  • 3
  • 8
  • 32

2 Answers2

4

You can respond to the TextChanged event on textBox1 to trigger some action in your code. Warning: be sure to sanitize your inputs!

CSJ
  • 3,641
  • 2
  • 19
  • 29
  • 1
    This is correct, but he may find a small problem when changing the values, for example if the textbox is empty than the database may return an error. I mean that for every value that is changed the query will be executed and this may give a problem. – Mike B Jul 14 '13 at 23:24
  • i did not get the last statment "Sanitize your input" – Haider Khattak Jul 14 '13 at 23:26
  • after entering the number in textbox1 i want it automatically to show the result in textbox 2. – Haider Khattak Jul 14 '13 at 23:28
  • 1
    @HaiderKhattak: Using the contents of a text box directly in the text of a database query is bad practice, and exposes you to [SQL Injection attacks](http://en.wikipedia.org/wiki/SQL_injection). All inputs must be _sanitized_ before inclusion in a query. – CSJ Jul 14 '13 at 23:32
  • can you please correct the code or send me an type an example from which i can get an idea? – Haider Khattak Jul 14 '13 at 23:37
  • Try [here](http://stackoverflow.com/questions/8234971/adding-parameters-to-idbcommand). – CSJ Jul 14 '13 at 23:56
  • Documentation and examples available [here](http://msdn.microsoft.com/en-CA/library/system.data.idbcommand.parameters(v=vs.71).aspx) – CSJ Jul 14 '13 at 23:57
0

Search if there is any OnExit event, so after editing the first textbox the second will be updated automatically.

Mike B
  • 1,522
  • 1
  • 14
  • 24