I'm receving an Index out bounds error
on the FullName property
below. I have my persondetails
class and data
class where I am using a SqlDataReader
trying to call this property. The firstname
and lastname
values are returned using a stored procedure and then I wanted to create a property to concatenate these 2 and just be able to call FullName
in my stored Procedure.
persondetails
class
private string firstName;
private string lastName;
private string fullName;
public string FirstName
{
get { return firstName;}
set { set firstName = value;}
}
public string LastName
get { return lastName; }
set { set lastName = value; }
public string FullName
get { return lastName + "," + firstName;
}
public persondetails(string lastName, string firstName)
{
this.lastName = lastName;
this.firstName = firstName;
}
data
class
public List<Persondetails> getFullName()
{
// Do my sql connection stuff
List<Persondetails> persondetails = new List<Persondetails>();
Persondetails person;
try
{
// open connection
// specify "stored Procedure" (which returns firstname and lastname)
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
person = new Persondetails((
reader.GetString(reader.GetOrdinal("LASTNAME")));
reader.GetString(reader.GetOrdinal("FIRSTNAME")));
persondetails.Add(person);
}
reader.Close();
return persondetails;
}
// the rest of my method
Stored Procedure simply returns lastname
and firstname
from my table which has 2 seperate fields. I do not want to do the concatenation here I would like to do it in my properties.
EDITED*** Working Code
You don't have a column returned from your stored procedure named "FullName" is the problem. That's why you get the error.
If your stored procedure returns FirstName and LastName you need to store those in their appropriate properties.
I would expect you to have a method that populates your class from the database... and in it something like this...
FirstName = reader.GetString(reader.GetOrdinal("FirstName")));
LastName = reader.GetString(reader.GetOrdinal("LastName")));
That would populate your FirstName and LastName in your class.... then your FullName property would work since it just concatenates FirstName and LastName.