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

Getting SQL to work from C# with Dates
Store Enum as Char with Dapper
Drag and Drop Windows Forms: Controls dissapear after dragging
What is the best way to count all instances of a single process running under a particular user logon?
C# Security Protocol Specification
Ajax Dropdownlist using cascading dropdownlist in asp.net
Adding textbox value with button in C#
How to show the tooltip without any time duration?
How can i hide in game view a ui button and show the button when pressing the escape key?
TCP Connection. best way to handle multiple connections [duplicate]
Send POST request with Image from Unity3D
How to make default Password Reset functionality work in ASP.NET Core
UriTemplate Matching Email
Error handling between web api and angular 2 client
Get Duplicates in List and Edit Item
Should I await a 'async Task' function if I don't care its return value? [duplicate]

Categories

HOME
gcc
kendo-ui
azure-active-directory
salesforce
postgresql-9.3
packet
liquibase
reference
highmaps
x86-64
hiveql
grid
uml-designer
foreach
webpack-dev-server
ephesoft
pyodbc
activejdbc
aspectj
fine-uploader
yui
openscad
pylint
orange
aws-devicefarm
bug-reporting
vala
android-navigation-drawer
visual-studio-community
gulp-jshint
multiple-inheritance
emr
restangular
r-factor
semantic-ui-react
jboss-arquillian
foxpro
wordpress-rest-api
login-required
loopback
unity3d-5
android-scrollview
angularjs-resource
wit-ai
campaign-monitor
kdevelop
console.readline
libconfig
idea-plugin
quartz
web-technologies
vpython
amazon-fire-tv
ocpjp
niagara-ax
reqif
automapper-4
history
monaca
appcmd
perldoc
tsc
suitesparse
toggleclass
ldd
git-push
hdr
geokit
jde
database-administration
android-contentresolver
jcomponent
javapackager
om
traminer
tess4j
clearquest
data-representation
connection-timeout
ios-enterprise
time-frequency
step
db2-connect
php-amqplib
xtify
mahara
mencoder
ojb
nsnumber
usersettings
friendly-url
pyxplot
outlook-object-model
pudb
vline
yii-components
junit-rule
orchestration
m3u
beep
animationdrawable
code-organization
httppostedfilebase
cinder
lgpl
google-local-search
database-agnostic
webdb
pixel-bender
content-delivery-network
vista64
jettison

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