0

I would like to know how to enable button based on mysql value.

I have database called database. Inside database table users and row uploader (varchar(45)) text in row is "True".

Here is my code ... but it doesn't work. Any solution would be great.

try
{
    string myConnection = "datasource=localhost;port=3306;username=root;password=pass";
    MySqlConnection myConn = new MySqlConnection(myConnection);

    MySqlCommand SelectCommand = new MySqlCommand("select uploader from database.users where username='" + c.username_txt.Text + "' ;", myConn);
    MySqlDataReader myReader;
    myConn.Open();
    myReader = SelectCommand.ExecuteReader();
    while (myReader.Read())
    {
        Console.WriteLine(myReader.GetString(myReader.GetOrdinal("uploader")));
    }
    string uploader = Console.ReadLine();
    if (uploader == "True")
    {
        uploadToolStripMenuItem.Enabled = true;
    }
    else
        myConn.Close();
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}
6
  • 1
    What do you mean it doesn't work? Any exception or error message? Commented Oct 22, 2013 at 14:09
  • you should really put your connection in a using statement. This would handle the closing of the connection, even if there is an exception. Commented Oct 22, 2013 at 14:10
  • And please use parameterized queries. Also use using statement for your connections. Commented Oct 22, 2013 at 14:10
  • if (uploader == "True") it's possible this case-sensitive comparison is failing, depending on what's in your database. You really should store boolean values if it's a boolean field. Commented Oct 22, 2013 at 14:11
  • where are you disabling the button? is it already disabled? Commented Oct 22, 2013 at 14:14

1 Answer 1

1
if (uploader == "True")
{
    uploadToolStripMenuItem.Enabled = true;
}
else
{
    myConn.Close();
    uploadToolStripMenuItem.Enabled = false
}

if uploadToolStripMenuItem is already enabled and you want it disabled when uploader != "True", then you have to disable it explicitly. Something else about your code, uploader won't be assigned any data from the table, but user input from the console (CLI), which doesn't make much sense since your working with buttons (GUI). to assign the value of the database call to the var, and keep the code like it is, do:

string uploader;
while (myReader.Read())
{
    uploader = myReader.GetString(myReader.GetOrdinal("uploader"))
    Console.WriteLine(uploader);
}

this will set uploader to the value of the uploader column in the last row

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.