c#


InvalidCastException was unhandled in datagridview


My program stops whenever I press the blank row of the DataGridView in my form. The error says:
InvalidCastException was unhandled.
This is the part of the code where the error is happening:
private void dataGridView1_Click(object sender, EventArgs e)
{
id = Convert.ToInt32(dataGridView1.SelectedCells[0].Value); //This is the line with the error
textBox1.Text = dataGridView1.SelectedCells[1].Value.ToString();
textBox2.Text = dataGridView1.SelectedCells[2].Value.ToString();
textBox3.Text = dataGridView1.SelectedCells[3].Value.ToString();
textBox4.Text = dataGridView1.SelectedCells[4].Value.ToString();
}
As you've just said:
program stop whenever i press the blank row
and then you've got
id = Convert.ToInt32(dataGridView1.SelectedCells[0].Value); //This is the line with the error
It will always fail, because Int is value type and cannot be null, and when you've got empty row the value on this cell will be most likely null.
Try something like this:
try
{
id = Convert.ToInt32(dataGridView1.SelectedCells[0].Value); //This is the line with the error
textBox1.Text = dataGridView1.SelectedCells[1].Value.ToString();
textBox2.Text = dataGridView1.SelectedCells[2].Value.ToString();
textBox3.Text = dataGridView1.SelectedCells[3].Value.ToString();
textBox4.Text = dataGridView1.SelectedCells[4].Value.ToString();
}
catch(InvalidCastException exception)
{
// not much to do with it, you can display assign empty valuest to your text boxes or notify user that there's nothing to select
}
Alternate apporach could be checking if the cell has value.
if(string.IsNullOrWhiteSpace(dataGridView1.SelectedCells[0].Value))
{
return;
}
id = Convert.ToInt32(dataGridView1.SelectedCells[0].Value);
//Assign values to textboxes
And there's also another possibility:
int id;
if(int.TryParse( dataGridView1.SelectedCells[0].Value.ToString(), out id ))
{
//Assign values to textboxes
}
An error is being thrown because the selected cell is trying to be converted to an integer regardless of what the value is.
Try checking if the cell has a value before converting to an integer.
//create a selected row variable
int selectedrowindex = dataGridView1.CurrentRow.Index;
DataGridViewRow selectedRow = dataGridView1.Rows[selectedrowindex];
//convert the selected cell from a string to integer
string idString = Convert.ToString(selectedRow.Cells[0].Value);
//create an integer only if there is a value in the cell.
if (idString.Trim() != ""){
id = Int32.Parse(idString);
}
Hope this helps!
What is the datatype of first grid cell?
The variable you are trying to convert is non-numerical or some special character datatype, and that is why it is causing an error. I suggest you to use the convert.toString() method if you want to use non-numerical or a combination of non-numerical and numerical data.

Related Links

Mock abstract protected method
How to add a looping selector to a Windows Phone 8.1 app?
AccessViolationException after copying a file from inside a zip archive to the clipboard and handling its data
How can I easily create a Func<T> from a method name?
C# Generic Passing different objects with same properties
Issue with Photometric Interpretation tag
Fixing possible memory leak in RelayCommand
Draw control like Google chrome
Expression tree creation with TryParse and Convert C#
Best way to keep a list in a wcf service memory
Gala type of game list of missile and list of asteroid collisions
MVC map Viewmodels to domain models
OpenGL transformations not working as expected
How do I join strings from a List<string> while also formating them?
how to select latest item on top of the list and rest of the item in sorted order
Convert Image to Bytes and save in Xml

Categories

HOME
classification
oop
arguments
query-string
revit-api
wkhtmltopdf
rename
google-my-business-api
digital
jpql
vichuploaderbundle
decoding
websharper
adroitlogic
captcha
element
repeater
sha1
taxonomy
udeploy
descriptor
bug-reporting
quality-center
policy
gsuite
android-wear-2.0
android-xml
continuous-fourier
rollupjs
libxml2
large-files
scripting-language
bytebuffer
units-of-measurement
pushpad
paper-trail-gem
xlib
edsdk
postgresql-9.6
unity3d-5
n1ql
angularjs-resource
gstreamer-1.0
scalamock
file-conversion
pyexcel
mtm
firefox-developer-edition
grails-2.0
ocamlbuild
serialversionuid
iban
sqlproj
distcc
mavlink
dimensionality-reduction
access-violation
boost-range
instaparse
shtml
ideavim
github-for-mac
angular-promise
sdkman
database-project
transbase
dpkt
xml-simple
p4python
euro
vectordrawable
stderr
jad
mri
dockerpy
applinks
crystal-reports-7
gnip
selenium-grid2
switchpreference
visual-studio-setup-proje
dateadd
sigma-grid-control
image-preloader
carrier
imaplib
ironworker
kohana-orm
angularjs-select2
pyxplot
pudb
vline
antixsslibrary
zepto
freeimage
expresso-store
databus
bindinglist
advanceddatagrid
clgeocoder
qvariant
method-call
auto-compile
xhtmlrenderer
cryptolicensing
response-time
nyromodal
simultaneous
chromebug
system-analysis
authkit
cstring
vista64

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App