Click here to Skip to main content
15,886,026 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
int ScriptId = 0;

     string sql = "Select Max(ScriptId) as ScriptId from tbl_Script";
SqlCommand cmd = new SqlCommand(sql, connection);
                SqlDataReader reader = cmd.ExecuteReader();
                reader.Read();

if (reader.HasRows)
                {
                    while (reader.Read())
                    {


                        if (reader["ScriptId"] == System.DBNull.Value)
                        {

                            ScriptId = 1;
                        }
                        else
                        {
                            ScriptId = ScriptId++;
                        }
                    }
                }

Hi All
I am creating a winform application in c#.and using sql database.
I have one table, tbl_Script, which has columns like tblScript_Id, and ScriptId. tblScript_Id is auto increment and all other datatypes are Integer .
I want store the value in var ScriptId. but if i am get null value want to store 1 or if get 1 want to store in var 2.
But I am get error in the line
C#
if (reader["ScriptId"] == System.DBNull.Value)


IndexOutOfRangeException was Unhandaled pla help
Posted

1 solution

Try reader[0] instead of ScriptId.
 
Share this answer
 
Comments
Arjunwalmiki 15-Feb-14 2:21am    
int ScriptId = 0;

string sql = "Select Max(ScriptId) as ScriptId from tbl_Script";
SqlCommand cmd = new SqlCommand(sql, connection);
SqlDataReader reader = cmd.ExecuteReader();
reader.Read();

if (reader[0] == System.DBNull.Value)
{

ScriptId = 1;
}
else
{
int i = Convert.ToInt32(reader["ScriptId"].ToString());
ScriptId = (i + 1);
}

}

thank you abhinav my problem was solve i have done change as you told me my correct code is look like this but dude if i am recived null value from table i want to set one

if (reader["ScriptId"] == System.DBNull.Value)
{

ScriptId = 1;// is this right or ?
}

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