Click here to Skip to main content
15,392,944 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
I am trying to edit the data in the ListBox that's stored in SQL server using the MouseClick event but I am getting this error
"Input string was not in a correct format"

What I have tried:

private void Data_listBox_MouseClick(object sender, MouseEventArgs e)
            var selectedValue = Data_listBox.SelectedItem;
            if (selectedValue == null)

            string StudentData = Data_listBox.SelectedItem.ToString();
            string[] Field_Data = StudentData.Split('_');
      //ERROR APPEARS FOR THE LINE BELOW "Input string was not in a correct format"
             visit_ID = Int16.Parse(Field_Data[0]);
Updated 19-Jun-22 23:00pm

At the time the
visit_ID = Int16.Parse(Field_Data[0]);
is executed, Field_Data[0] does NOT contain a valid representation of a Int16.
You could easily verify it using the debugger.
To handle such scenarios, please have a look at the 'Remarks' section of FormatException Class (System) | Microsoft Docs[^].
Consider using Int16.TryParse Method (System) | Microsoft Docs[^] instead: it returns a true / false code instead of throwing an exception, so your code can handle the problem gracefully instead of crashing.

Something in your data is causing the underlying problem: it either isn't a number, isn't in the right place, or is too big for a 16 bit number. Often this is a result of a poor data source design, but we can't help you identify anythign data related as we have no access to it.

So, it's going to be up to you.
Fortunately, you have a tool available to you which will help you find out what is going on: the debugger. If you don't know how to use it then a quick Google for "Visual Studio debugger" should give you the info you need.

Put a breakpoint on the first line in the function, and run your code through the debugger. Then look at your code, and at your data and work out what should happen manually. Then single step each line checking that what you expected to happen is exactly what did. When it isn't, that's when you have a problem, and you can back-track (or run it again and look more closely) to find out why.

Sorry, but we can't do that for you - time for you to learn a new (and very, very useful) skill: debugging!

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