Click here to Skip to main content
15,799,017 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
int Number = int.Parse(dr.GetString(0));

find the above code , am going to fetch the customer_ID from DB to front end dropdown ..

whule featching data am facing this error messahe .

can you please help me for the same

What I have tried:

           string str = "select * from Tblcustomer";
           SqlCommand cmd = new SqlCommand(str, con);
           SqlDataReader dr = cmd.ExecuteReader();
           while (dr.Read())
               int Number = int.Parse(dr.GetString(0));
Updated 25-May-20 0:27am

Well it could be time to learn how to debug, ie, set a break-point in code then single-step and also think about the code you have written ..

I'd say from a quick look, that
int Number = int.Parse(dr.GetString(0));
could be problematic, one would have to wonder why you're getting the number as a string (which the error messages is saying 'I cant do that') - then parsing it

.. If the column in the database IS numeric, let's assume an integer, then why not
int Number = (dr.GetInt32(0));

Also, if you're going to post question(s) about a database, did you not think to include a brief definition of the relevant table ?

Maybe you could also study whatever reference materials you have or google 'C# datareader' to see how to get columns of various data-types
Share this answer
Maciej Los 25-May-20 5:27am    
In addition to solution #1 by Garth J Lancaster
Why to load full table instead of interesting part only?
Replace this:
select * from Tblcustomer

select NameOfFieldYouWantToGet from Tblcustomer

BTW: ComboBox[^] control has several useful properties, such as:
DataSource Property (System.Windows.Forms) | Microsoft Docs[^]
DisplayMember Property (System.Windows.Forms) | Microsoft Docs[^]
ValueMember Property (System.Windows.Forms) | Microsoft Docs[^]

Conclusion: If you want to load customer data, you can do that this way:
DataTable dt = new DataTable();
string str = "select CustomerID, CONCAT(LastName, ' ', LEFT(FirstName, 1)) AS CustomerName from Tblcustomer";
SqlCommand cmd = new SqlCommand(str, con);
SqlDataReader dr = cmd.ExecuteReader();
combocustomer.ValueMember = "CustomerID"
combocustomer.DisplayMember = "CustomerName";
combocustomer.DataSource = dt;

Final note: use using(disposable_object do = new disposable_object) statement to "auto-manage" disposable objects. See: Using objects that implement IDisposable | Microsoft Docs[^]
DataTable dt = new DataTable()
using(SqlConnection connection = new SqlConnection("connectionstring_here"))
    using(SqlCommand command = new SqlCommand("commandtext_here"), connection)
        using(SqlDataReader reader = command.ExecueReader())
//further instructions here
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900