André
André

Reputation: 37

Get the value from cell as integer DATAGRIDVIEW C#

I'm trying to create a general method to update my database for all my classes. I have a primary key, so when I want to update something I say "Do this, where id = @id"

My question is how can I get the value of primary key in my datagridview as an integer to pass as an argument to my update method. I need a int value because I know how to make with string. It must be an int value.

Upvotes: 0

Views: 382

Answers (1)

Markiian Benovskyi
Markiian Benovskyi

Reputation: 2161

You should use int.Parse to correctly parse string to integer.

But I would advice you to use string.TryParse if you are not sure about the contents of your cell:

int result = -1;
bool parsed = int.TryParse(dataGridView1.CurrentCell.Value.ToString(), out result);

And then in your code:

if(parsed) {
    // everything ok, use result here
} else {
    // something wrong with parsing
}

Upvotes: 1

Related Questions