user3099540
user3099540

Reputation: 1

Unhandled exception due to the comboBox1 is a control

When ever I attempt to login it throws up unhandled exception due to the comboBox1 is a control

Can someone tell me how to fix this?

I am making the ComboBox1 due to I want a dropdownlist with the usernames.

But for it to verify the username and password It must select the username in combo box + Password If password matches to the username = Allowed to login.

private void Button1Click(object sender, EventArgs e)
{
  var dt = new DataTable();
  const string Connectionstring = "Data Source=GARETH-PC1;Initial  Catalog=Genres;Integrated Security=True";
  using (var con = new SqlConnection(Connectionstring))
  {
    con.Open();
    var query = "Select Username From Login Where Username ='" + comboBox1 + "' and Password ='" + textBox2.Text + "'";
    using (var sda = new SqlDataAdapter(query, con))
    {
      sda.Fill(dt);
    }
  }

  if (dt.Rows[0].ItemArray.GetValue(0).ToString() == "1")
  {
    Hide();
    var ss = new Main();
    ss.Show();
  }
  else
  {
    MessageBox.Show("Invalid Username or Password");
  }
}

Upvotes: 0

Views: 42

Answers (1)

Alex Walker
Alex Walker

Reputation: 2356

In this line:

var query = "Select Username From Login Where Username ='" + comboBox1 
    + "' and Password ='" + textBox2.Text + "'";

You're trying to concatenate a String and a Control together. (ComboBox is a subclass of Control) This is not allowed. What you need to use is the SelectedText property of ComboBox:

var query = "Select Username From Login Where Username ='" + comboBox1.SelectedText 
    + "' and Password ='" + textBox2.Text + "'";

Incidentally, I would strongly advise using prepared statements to ensure users don't enter their own SQL code into the username and password fields, and potentially compromise the security of your database. This usually involves setting the query string with parameter names (val0, val1 etc.) instead of the raw text comboBox1.SelectedText, textBox2.Text.

Information on prepared statements in Microsoft SQL: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.prepare(v=vs.110).aspx

Information on prepared statements in MySQL: http://dev.mysql.com/doc/refman/5.0/en/connector-net-programming-prepared.html

Upvotes: 1

Related Questions