Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning a DataTable value to a Variable

I just wrote a simple method to get some data from an SQL server and store it in a DataTable.

Specifically the value is an integer : 666

It is an int datatype on the database and I made a variable called Credits in C# which is also an integer.

The datatable shows the value 666 in the first row so it got added without any problems.

The problem happens when I try to assign Credits = dt.Rows[0] saying

the inputstring was an incorrect format

Ive tried parsing it to an int and adding .ToString() but no matter what it gives the same error.

the latest line I tried was

Credits = Convert.ToInt32(dt.Rows[0].ToString());

But still no luck. I have looked everywhere online for a solution but I cannot find the problem. Any help would be greatly appreciated.

like image 892
Sidney Avatar asked Aug 16 '26 13:08

Sidney


1 Answers

You are missing column name while selecting data from Data Table. You can either use column name or column index.

int Credits = Convert.ToInt32(dt.Rows[0]["columnname"].ToString());

Please make sure that value of that column value should not be null or empty.If thats the case you have to check that before assigning to int variable.

Or You can use, TryParse

int Credits = int.TryParse(dt.Rows[0]["columnname"].ToString());
like image 83
HaveNoDisplayName Avatar answered Aug 18 '26 03:08

HaveNoDisplayName



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!