0

I'm new to c# and I've using xampp for mysql connection with visual studio. I'm trying to View list box selected item data that is connected to sql database table to text field when the item is clicked. I'm using this code but nothing happens when i click the item..

private void listbox_user_SelectedIndexChanged(object sender, EventArgs e)
{
    MySqlConnection sqlcon = new MySqlConnection("Server=localhost;Database=table1;Uid='root';Pwd='';SslMode=none");
    sqlcon.Open();
    MySqlCommand cmd = sqlcon.CreateCommand();
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = "SELECT * FROM login WHERE Name='"+listbox_user.SelectedItem.ToString()+"'";
    cmd.ExecuteNonQuery();
    DataTable dt = new DataTable();
    MySqlDataAdapter da = new MySqlDataAdapter(cmd);
    da.Fill(dt);
    foreach(DataRow dr in dt.Rows)
    {
         txtbox_name.Text = dr["Name"].ToString();
         txtbox_username.Text = dr["Username"].ToString();
         txtbox_pwd.Text = dr["Password"].ToString();
    }
    sqlcon.Close();
}

The database is connected and the data is there but nothing happens

here is form design

urmat abdykerimov
  • 427
  • 1
  • 7
  • 17
asdf
  • 13
  • 4
  • Possible duplicate of [C# and MySQL .NET Connector - Any way of preventing SQL Injection attacks in a generic class?](https://stackoverflow.com/questions/2775692/c-sharp-and-mysql-net-connector-any-way-of-preventing-sql-injection-attacks-i) – mjwills Aug 21 '18 at 13:37
  • https://stackoverflow.com/questions/14376473/what-are-good-ways-to-prevent-sql-injection may be worth reading. – mjwills Aug 21 '18 at 13:41
  • Run to the breakpoint on the `foreach` line. Type `?listbox_user.SelectedItem.ToString()` into the `Immediate Window`. What appears? What about for `?dt.Rows.Count`? – mjwills Aug 21 '18 at 13:56
  • The result i got is this ?dt.Rows.Count 0 ?listbox_user.SelectedItem.ToString() "System.Data.DataRowView" – asdf Aug 21 '18 at 14:05
  • You really should be using `using` statements. https://stackoverflow.com/a/17592858/1684720 as an example of how to do so. – gattsbr Aug 21 '18 at 15:13
  • I'd suggest having a read of https://stackoverflow.com/questions/23865113/when-i-get-selecteditem-in-combobox-return-system-data-datarowview . – mjwills Aug 21 '18 at 23:36

0 Answers0