1

I have a little trouble using C# combobox with MySql

So, to begin with... I have combobox and button on a form. After submitting a form, executes MySql query like :

"select * from db1.users where login='"+combobox.SelectedIndex+"')";

It works great, But.... if we submit the first element of combobox - MySql FOREIGN KEY problem occures (= NULL and so on).

Any Ideas how to give him know, that first element from combobox isn't NULL ?

Malakai
  • 3,011
  • 9
  • 35
  • 49

4 Answers4

0

Are you sure what you want isn't combobox.SelectedItem? This would be the case if "login" was a string in the SQL database. If it's an integer, have you tried doing combobox.SelectedIndex+1? This could fix the problem if "login" starts at "1" in the SQL whilst SelectedIndex starts at 0 in C#.

In any case, check the answer below if your problem is the combobox having no selected item. Optionally you can have the form OnLoad do combobox.SelectedItem=1;

0

I'll assume you're talking about just submiting the button without actually selecting a value on the combobox, right?

You should do a simple if before executing your command, like:

if (combobox.SelectedIndex != null)
{
  codethis("select * from db1.users where login='"+combobox.SelectedIndex+"')");
}
else
{
  //do something else
}
0

Stupid idea but who knows: Mysql counts from 1, combobox from 0 did you try:

(selectedIndex + 1)
roxik0
  • 97
  • 6
0

You would want to stop using SelectedIndex, because it's not meant to represent your data. The problem may not even be in your current situation (mismatch between 1s and 0s indexing). Consider the following:

  • Another developer adds sorting to your combox. Now instead of a,b,c the values are c,b,a and the selected index of 0 will now point to c instead of a as it has used to do
  • Somebody removes users in the database, so in the database you now have b,c,d, think about what data you will have in your combobox?

To fix this problem you should use a value. Each combobox should have: displayed text, corresponding value (which is hidden from user) and selected index. Using selected index (or selected item) you get the item's value which should be your database_id. For example see this answer if the value is not available for your combobox type out of the box.

Bonus points:

  • use parameterised queries (prevents SQL injection attacks)
  • never store passwords, instead store password hashes and random salts (read more)
Community
  • 1
  • 1
oleksii
  • 35,458
  • 16
  • 93
  • 163