-2

i want to convert what i selected from the combobox so i can edit it or delete it, but the messege "cannot convert from string to int" keep showing

if (sqlCon.State == ConnectionState.Closed)
            sqlCon.Open();
        string Query = "select * from tbl_article where NameArticle='"+comboBoxArt.Text+"'";
        SqlCommand cmd = new SqlCommand(Query, sqlCon);
        SqlDataReader myReader;
        try
        {
            myReader = cmd.ExecuteReader();
            while (myReader.Read())
            {
                txtName.Text = myReader.GetString("NameArticle");
                txtPrice.Text = myReader.GetInt32("PriceArticle").ToString();
            }
        }

and also when i run it, the selected item changes to his id "IdArticle". how can i fix this ??

Jalloul95
  • 206
  • 1
  • 2
  • 10

1 Answers1

3

Why not just do this?

txtName.Text = myReader["NameArticle"].ToString();
txtPrice.Text = myReader["PriceArticle"].ToString();

It should get whatever value from database whether its int or DateTime etc then convert it to string?

P. Pat
  • 488
  • 4
  • 13
  • still one thing, when i select an item from the combobox, the item switchs to his ID in the combobox – Jalloul95 Mar 23 '17 at 04:34
  • this is the best answer, it's easy to do a TryParse to the text later on if you need the value back as a number. As to your second question, i don't understand it at all. – ferday Mar 23 '17 at 04:36
  • @AbdelJelilZaghouani that is due to your query `where NameArticle='"+comboBoxArt.Text+"'`. I suggest you start practicing parameterized query and also use `Add` instead of `AddWithValues`. [About Parameter](http://stackoverflow.com/questions/7505808/why-do-we-always-prefer-using-parameters-in-sql-statements) & [Why stop AddWithValues](http://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/) – P. Pat Mar 23 '17 at 04:42
  • @ferday so, the combobox shows articles names from a table called tbl_article, the article have an id(IdArticle), a name(NameArticle) and a price(PriceArticle), when i select an article from the combobox, the name changes to the ID in the combobox – Jalloul95 Mar 23 '17 at 04:46