-4

If a textbox value has changed, how can I select from a database by the new textbox value and not the old value?

string constring = "datasource=127.0.0.1;username=root;password=admin";
string Query = "select * from mohamed.usercompany1 where office  =  '" + textBox1.Text + "'  ;";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
DataSet DataSet1 = new DataSet();
MySqlDataReader myReader;
try
{
    conDataBase.Open();
    myReader = cmdDataBase.ExecuteReader();
    if (myReader.Read())
    {
        string scode = myReader.GetInt32("techname").ToString();
        textBox1.Text = (string)myReader["techname"];
        comboBox2.Items.Add(scode).ToString();
        listView1.Items.Add(scode).ToString();
        this.Refresh();
    }
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}
PiotrWolkowski
  • 8,408
  • 6
  • 48
  • 68
  • Little Bobby tables.... `textBox1.Text = '; DROP TABLE mohamed.usercompany1 -- `http://stackoverflow.com/questions/332365/how-does-the-sql-injection-from-the-bobby-tables-xkcd-comic-work – Nico Apr 10 '15 at 06:04

1 Answers1

1

You can add a handler for the TextChanged event. It is raised when the text is changed.

private void textBox1_TextChanged(object sender, EventArgs e)
{
    //textBox1.Text contains the new Text now
    //execute your SQL...
}

But you should be careful. It is possible to input a SQL statement in the TextBox, which damages the database. It is more secure to use Parameters:
Parameterized Query for MySQL with C#

Community
  • 1
  • 1
Koopakiller
  • 2,838
  • 3
  • 32
  • 47
  • this only for get result not for inserted to database same way to do this ??? – TopMzzika. Com Apr 09 '15 at 22:58
  • @TopMzzika.Com You can simply execute your code in that event handler, so the SQL contains the new value of the TextBox. – Koopakiller Apr 09 '15 at 23:01
  • am try too much for this but until now i no get the new result for new value , am nooby in c# :S if possible any tutorial for this operation – TopMzzika. Com Apr 09 '15 at 23:11
  • @TopMzzika.Com If you get still the old result, then the Problem is not caused by the TextBox. There must be another Problem in your DB query. There are much tutorials in the web, for example: http://www.codeproject.com/Articles/43438/Connect-C-to-MySQL – Koopakiller Apr 10 '15 at 00:37
  • maybe but comboBox1 working fine and give me the names of department , the problem here comboBox1 selected items request ID and save it in this textbox ,and i make request be id shown result in combobox2 bu this happend for 1 time only , if i change select items in no 1 textbox update but combox2 still no update – TopMzzika. Com Apr 10 '15 at 00:48