I am having trouble understanding why I am getting this exception thrown !
This is the code :
public static List<Employee> LoadEmployees()
{
List<Employee> emp = new List<Employee>();
try
{
using (SQLiteConnection cnn = new SQLiteConnection(LoadConnectionString()))
{
cnn.Open();
string query = "select * from Employee;";
SQLiteCommand cmd = new SQLiteCommand(query, cnn);
using (var reader = cmd.ExecuteReader())
{
int i = 0;
while (reader.Read())
{
emp[i].Id = reader.GetString(0);
emp[i].Name = reader.GetString(1);
emp[i].Gender = reader.GetString(2);
emp[i].Department = reader.GetString(3);
emp[i].Doj = reader.GetString(4);
emp[i].Email = reader.GetString(5);
emp[i].Phone = reader.GetString(6);
i++;
}
}
return emp;
}
}
catch (Exception ex)
{
emp = null;
return emp;
}
}
I tried debugging and found that - id = 'emp[i].Id' threw an exception of type 'System.ArgumentOutOfRangeException' Exception thrown: 'System.ArgumentOutOfRangeException' in mscorlib.dll
I am not understanding why it throwing it because i have initialized i = 0;
List<Employee> emp = new List<Employee>();
At this point, emp is empty, but you try accessing items by using emp[i] when it's still empty.
You should use emp.Add(new Employee()); at some point if you don't want the list to be empty anymore.
public static List<Employee> LoadEmployees()
{
List<Employee> emp = new List<Employee>(); // basically you have created new List<Employee> which is at the moment is empty. so if you try to do emp[0].Name, you will get exception
try
{
using (SQLiteConnection cnn = new SQLiteConnection(LoadConnectionString()))
{
cnn.Open();
string query = "select * from Employee;"; // fetching employees from database
SQLiteCommand cmd = new SQLiteCommand(query, cnn);
using (var reader = cmd.ExecuteReader())
{
int i = 0;
while (reader.Read())
{
Employee e = new Employee(); // create new instance of employee object and initialize it's members and then add it in emp object.
e.Id = reader.GetString(0);
e.Name = reader.GetString(1);
e.Gender = reader.GetString(2);
e.Department = reader.GetString(3);
e.Doj = reader.GetString(4);
e.Email = reader.GetString(5);
e.Phone = reader.GetString(6);
emp.Add(e);
}
}
return emp;
}
}
catch (Exception ex)
{
emp = null;
return emp;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With