Click here to Skip to main content
15,888,286 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi mates !!!
I am using this.
C#
DataTable objDt = new DataTable();
string a = objDt.Rows[0][0].ToString();
string b = objDt.Rows[1][0].ToString();
string c = objDt.Rows[2][0].ToString();


Query may return depends, that means may be 1,2 or 3. until 3 rows.

If query returns 2 rows, string c = objDt.Rows[2][0].ToString(); this statement has error.

Please Help
Posted
Updated 11-Feb-13 19:27pm
v2

Do a row count check before you access a row. So basically you check if a row exist or not before accessing it.
C#
string a , b, c;
if (objDt.Rows.Count > 0)
    a = objDt.Rows[0][0].ToString();
if (objDt.Rows.Count > 1)
    b = objDt.Rows[1][0].ToString();
if (objDt.Rows.Count > 2)
    c = objDt.Rows[2][0].ToString();
 
Share this answer
 
Hi,

ofcourse, datatable will throw error, if you try to access third row if the row count is 2.

if Row count is 2, then row index 0,1 can only be accessible. but you are trying access index 2, which exceeds the no. of rows.

so, string c = objDt.Rows[2][0].ToString() throw error if the row count is 2.


happy coding.:-)
 
Share this answer
 
you could have used Convert.Tostring()

It allows Null values and does not throw exception
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900