Struggling with some C# code

terencevs

Senior Member
Joined
May 12, 2006
Messages
782
Reaction score
8
Location
Cape Town
I recently started teaching myself C#. Decided to try out a little project with some of the knowledge I have gained but I am now a bit stuck.

I am creating an activation class where it will connect to a db validate the code and then return if the code is valid or not.

This is the error I get and I understand why I get it but I dont know how to solve it:

"IndexOutOfRangeException. there is now row at position 0"

Here is the code"

Code:
    class Activator2
    {
        public static string activate(string ActivationCode)
        {
            //Checks to see if the string ActivationCode is not null
            if (ActivationCode.Length > 0)
            {
                System.Data.SqlClient.SqlConnection con;
                DataSet dsl;
                System.Data.SqlClient.SqlDataAdapter da;

                con = new System.Data.SqlClient.SqlConnection();
                dsl = new DataSet();

                //Database Connection Configuration
                con.ConnectionString = "Data Source=TERENCEVS-XP;Initial Catalog=Activator;Integrated Security=True";

                //Open Connection
                con.Open();

                string sqlselect = "select ActivationCode from ActivationCodes where ActivationCode = '";
                string singlequote = "'";
                
                //Building select statement
                string sql = sqlselect + ActivationCode + singlequote;

                da = new System.Data.SqlClient.SqlDataAdapter(sql, con);

                da.Fill(dsl, "ActivationCodes");
                
                //Closing Conection
                con.Close();

                DataRow dRow = dsl.Tables["ActivationCodes"].Rows[0];

                if (ActivationCode == dRow.ItemArray.GetValue(0).ToString())
                {
                    return "1";
                }
                
                
                return "0";
            }

            return "No Activation Code Entered. Please enter a Code!";

Can someone please help me? :)
 
Step through the code and see which line is failing? My quick guess is at (ActivationCode == dRow.ItemArray.GetValue(0).ToString())
 
If I put the right code in it works.

It fails on DataRow dRow = dsl.Tables["ActivationCodes"].Rows[0];
 
just a tip...
change: if (ActivationCode.Length > 0)
to: if(!string.IsNullOrEmpty(ActivationCode)){}
Its easier and more accurate...

Like xrapidx said, step through and find the line where it fails...

Edit: Are you sure the table name is correct and the dataset contains the table called 'ActivationCodes' and it returns any rows?
 
Might be here as well:
DataRow dRow = dsl.Tables["ActivationCodes"].Rows[0];

If the table shas no rows
 
If you put the wrong code then no rows are returned. You need to check the dataset.rows.count property
 
if (dsl.Tables["ActivationCodes"].Rows.Count>0)
{
DataRow dRow = dsl.Tables["ActivationCodes"].Rows[0];
if (ActivationCode == dRow.ItemArray.GetValue(0).ToString())
{
return "1";
}
}

return "0";
 
AS "Mister" said:
Replace "
DataRow dRow = dsl.Tables["ActivationCodes"].Rows[0];

if (ActivationCode == dRow.ItemArray.GetValue(0).ToString())
{
return "1";
}
"
With
if (dsl.Tables["ActivationCodes"].Rows.Count >0 ){
DataRow dRow = dsl.Tables["ActivationCodes"].Rows[0];

if (ActivationCode == dRow.ItemArray.GetValue(0).ToString())
{
return "1";
}
.....
}
 
Thank you dequadin.

Like I said newbie and any help and direction is great!

Once again to all thanks!
 
Hi terencevs,

Don't bother using and filling a dataset when you only want to retrieve a single value. This is especially true if you only want to check if the row exists. Try out the following code instead:

Code:
        public static string activate(string ActivationCode)
        {
            string sResult = "";
            //Checks to see if the string ActivationCode is not null
            if (ActivationCode.Length > 0)
            {
                // Always wrap some error checking code around things that can fail
                try
                {
                    System.Data.SqlClient.SqlConnection con;
                    con = new System.Data.SqlClient.SqlConnection();

                    //Database Connection Configuration
                    con.ConnectionString = "Data Source=TERENCEVS-XP;Initial Catalog=Activator;Integrated Security=True";

                    //Open Connection
                    con.Open();

                    // Use parameters instead of string concatenation - ALWAYS please
                    string sqlselect = "select COUNT(ActivationCode) from ActivationCodes where ActivationCode = @activationcode";
                    
                    // Create the command object that will execute the sql
                    SqlCommand cmd = new SqlCommand(sqlselect, con);
                    cmd.CommandType = CommandType.Text;

                    // Add the parameter
                    cmd.Parameters.Add(new SqlParameter("@activationcode", SqlDbType.VarChar));
                    cmd.Parameters["@activationcode"].Value = ActivationCode;
                    
                    // ExecuteScalar returns the first column of the first row
                    // Should be 0 if it doesn't exist or 1 if it does
                    sResult = Convert.ToString(cmd.ExecuteScalar());

                    //Closing Conection
                    con.Close();
                }
                catch (Exception ex)
                {
                    sResult = ex.Message;
                }
            }
            else
            {
                sResult = "No Activation Code Entered. Please enter a Code!";
            }
            
            return sResult;
        }

I realise that there are probably a few statements in this code that you haven't learned yet. It also uses what is essentially my coding style and habit (such as a single return statement to reduce the chance of errors.) I hope you can learn from it.

Edit: Just seen dequadin's post
I agree with everything he has done except that ExecuteScalar() is far simpler in this particular case. See if you can replace the parts of his solution with the "scalar" parts of mine as an exercise.
 
Last edited:
To check if your dataset contains any data before using it:

if(dsl != null && dsl.Tables.Count > 0 && dsl.Tables[0].Rows.Count > 0)
{
DataRow dRow = dsl.Tables["ActivationCodes"].Rows[0];
{
 
Top
Sign up to the MyBroadband newsletter
X