简体   繁体   中英

Index out of range exception in asp.net

while trying to connect to the database i have written the following code in my page load method :

    SqlConnection con = new SqlConnection(constring);
    SqlCommand cmd = new SqlCommand();
    cmd.CommandType = CommandType.Text;
    cmd.Connection = con;
    con.Open();
    cmd.CommandText = "select pid from pid";
    SqlDataAdapter da = new SqlDataAdapter();
    DataSet ds = new DataSet();
    DataTable dt = new DataTable();
    da.SelectCommand = cmd;
    da.Fill(dt);
    a = Convert.ToInt32(dt.Rows[0][0].ToString()) + 1;
    con.Close();
    return a;

and im getting an error in the code line " a = Convert.ToInt32(dt.Rows[0][0].ToString()) + 1; " as: index out of range exception there is no row at position 0 how to proceed?

Presumably, your query is returning no rows. Handle accordingly (if it's possible that the query returns no rows, add an if statement). Otherwise, perhaps something is amiss with your query (selecting a column from an object of the same name doesn't seem right).

int retVal = default( int );

if( dt.Rows.Count == 1 )
{
    retVal = (int)dt.Rows[0][columnName];
}

return retVal;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM