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

opening a document and waiting for a user to finish editing it
Why is there no “date” shorthand of System.DateTime in C#?
Entity Framework - Why Does This Work?
Create a NHibernate Dialect that adds with(nolock) to every SELECT [duplicate]
I do not have a 'Any CPU' option present in my Configuration Manager
WCF Data Services, Entity Framework, LINQ -> Children within children
How do I determine the sender of an email via Exchange Web Services in C#?
c# fast sort and retrieve for small amount of key value pairs
MySQL Connector - removes polish characters
Project to create a book search website [closed]
C# visual control for editing statements / equations / conditions?
Generate new menus at timed intervals
Mongodb, linq driver. How to construct Contains with variable or statements
How do I retrieve a data type of tinyint from MySQL in C#?
DataTable Join using LINQ in C#
Second Unit Test Not Running

Categories

HOME
teradata
ftp
oracle-sqldeveloper
gsm
customization
xamarin.forms
mifare
pandoc
ubuntu-14.04
crash
sms
xss
multipartform-data
cdn
samsung-gear-s2
pyodbc
ejb-3.0
normals
openbsd
fastreport
console-application
infopath
owncloud
windows-phone
openam
indri
url-parameters
multipart
oracle-golden-gate
core-animation
checkmarx
ocl
mobile-development
overflow
multilanguage
directions
webmock
bootcamp
gitosis
dom4j
ragel
kofax
realloc
framebuffer
idea-plugin
julia-jump
azure-web-roles
file-descriptor
rexx
firefox-developer-edition
risc
logan-square
azure-data-catalog
anonymous-function
hierarchical-clustering
ng-class
perldoc
programming-pearls
overhead
apache-commons-cli
pyautogui
turbolinks
disconnect
rowname
tinybox2
csc
db2-zos
jmh
stdlist
jersey-test-framework
instabug
gnu-sort
ios8-share-extension
php-gd
traminer
tess4j
android-filterable
fileinputstream
opennebula
copy-on-write
maven-archetype
veeam
random-access
javadb
register-allocation
powershell-v1.0
ccmenuitem
rails-migrations
sendy
nsnumber
listpicker
xrandr
mosix
exi
architectural-patterns
nsregularexpression
mail-gem
teamsystem
motordriver
blackberry-eclipse-plugin
ios6-maps
scriptmanager
cgaffinetransform
time-management
atmega16
weak-typing
tracd

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