0

I have the following code:

using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TimeClock
{
    class Company
    {
        DataTable rows = new DataTable();

        public Company()
        {
            MySqlConnection connection = null;
            try
            {

                string connectionString = TimeClock.Properties.Settings.Default.timeclockConnectionString;
                connection = new MySqlConnection(connectionString);
                connection.Open();
                MySqlCommand command = new MySqlCommand("SELECT * FROM companies WHERE ID = @ID  LIMIT 1", connection);
                command.Parameters.AddWithValue("@ID", TimeClock.Properties.Settings.Default.CompanyID);
                MySqlDataAdapter da = new MySqlDataAdapter(command);
                da.Fill(rows);

            }
            catch (MySql.Data.MySqlClient.MySqlException ex)
            {
                Console.WriteLine(ex);
            }
            finally
            {
                if (connection != null)
                {
                    connection.Close();
                }
            }
        }

        public String getName()
        {
            DataRow row = rows.Rows[0];

            return row["company_name"].ToString();
        }
    }
}

I know why I'm getting this error: say that no records were found in the database, the of course row[0] will no exist, hence the exception. But how do I deal with when there are no records to store in the Datatable? By the way, I'm quite new to C# and any input would be great; feel free to criticize.

6
  • 2
    How about checking rows.Rows.Count is bigger than 0 or not? Commented Jul 2, 2015 at 6:58
  • I thought of that, but it would mean doing it for every method... I legitimately thought that that approach was wrong... Commented Jul 2, 2015 at 6:59
  • @Dimitri If you're concerned with code duplication, and it's good that you are, you could create a method to check the row count. That way, you may reuse it throughout your code. Commented Jul 2, 2015 at 7:05
  • Catch statement should be Console.WriteLine(ex.Message); btw. Commented Jul 2, 2015 at 7:06
  • 1
    @Dimitri Another way is to define a general method that performs the query. You would pass the command, along with the arguments, to it and you would get back the result. That way, you're not repeating the same code over and over... and all the error checking code would remain inside of it. Commented Jul 2, 2015 at 7:10

3 Answers 3

1

Before you access a collection

DataRow row = rows.Rows[0];

you'll have to make sure that the item exists:

if(rows.Count > 0) 
   DataRow row = rows.Rows[0];

always

Sign up to request clarification or add additional context in comments.

Comments

1

You must change getName function.

 public String getName()
 {
     if (rows.Rows != null && rows.Rows.Count > 0)
        {
            DataRow row = rows.Rows[0];
            return row["company_name"].ToString();
        }
        return string.Empty;
 }

Comments

0

To read data from SQL I'm doing it like so:

        using (SqlCommand SelectCommand = new SqlCommand(strbSelect.ToString()))
        {
                SelectCommand.Parameters.AddWithValue("Asset", AssetNumber);
                SelectCommand.Parameters.AddWithValue("Subnumber", Subnumber);

                SelectCommand.Connection = new SqlConnection(GetConnectionString());
                SelectCommand.Connection.Open();
                using (SqlDataReader Reader = SelectCommand.ExecuteReader())
                {
                    if (Reader.HasRows)
                    {
                        while (Reader.Read())
                        {
                            if (Reader[0] != DBNull.Value)
                            {
                                ReturnValue = Reader.GetBoolean(0);
                            }
                        }
                    }
                    else
                        return false;
                }
                SelectCommand.Connection.Close();
        }

StrbSelect is a StringBuilder.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.