DataReader problems getting data from 2 classes - c#

I am very inexperienced with SQL, and have only had one lesson. I am trying to figure out how to get information from 2 classes using a DataReader.
My Customer class:
public class Customer
{
private CreditCard _creditCard;
private List<Subscription> _subscriptions;
private int _customerId;
private string _name;
private string _address;
private int _zipCode;
private string _city;
private string _email;
private string _password;
public Customer(int id, string name, string email, string password)
{
this._customerId = id;
this._name = name;
this._email = email;
this._password = password;
this._subscriptions = new List<Subscription>();
}
public Customer(int id, string name)
{
this._customerId = id;
this._name = name;
_subscriptions = new List<Subscription>();
}
public override string ToString()
{
return _customerId + " " + _name;
}
public int CustomerId
{
get { return _customerId; }
set { _customerId = value; }
}
public string Name
{
get { return _name; }
set { _name = value; }
}
public string Address
{
get { return _address; }
set { _address = value; }
}
public int ZipCode
{
get { return _zipCode; }
set { _zipCode = value; }
}
public string City
{
get { return _city; }
set { _city = value; }
}
public string Email
{
get { return _email; }
set { _email = value; }
}
public string Password
{
get { return _password; }
set { _password = value; }
}
public List<Subscription> Subscriptions
{
get { return _subscriptions; }
}
public void AddSubscription(Subscription s)
{
_subscriptions.Add(s);
}
public Subscription FindSubscription(int sId)
{
bool found = false;
int i = 0;
while (!found && i < _subscriptions.Count)
{
if (_subscriptions[i].SubscriptionId == sId)
found = true;
else
i++;
}
if (found)
return _subscriptions[i];
else
return new Subscription();
}
}
My Subscription Class:
public class Subscription
{
private SubscriptionType _subscriptionType;
private CarModel _carModel;
private List<Booking> _bookings;
private int _subscriptionId;
public Subscription(int subscriptionId, SubscriptionType subscriptionType, CarModel carModel)
{
this._subscriptionId = subscriptionId;
this._subscriptionType = subscriptionType;
this._carModel = carModel;
_bookings = new List<Booking>();
}
public Subscription()
{ }
public int SubscriptionId
{
get { return _subscriptionId; }
set { _subscriptionId = value; }
}
public SubscriptionType SubscriptionType
{
get { return _subscriptionType; }
}
public CarModel CarModel
{
get { return _carModel; }
}
public override string ToString()
{
return this.SubscriptionId + "\t " + this.SubscriptionType + "\t " + this.CarModel;
}
}
My Database class:
public class DBCustomer
{
private static SqlCommand dbCmd = null;
public static List<Customer> GetCustomers()
{
List<Customer> returnList = new List<Customer>();
string sql = "select * from Customer";
dbCmd = AccessDBSQLClient.GetDbCommand(sql);
IDataReader dbReader;
dbReader = dbCmd.ExecuteReader();
Customer c;
while (dbReader.Read())
{
c = new Customer(Convert.ToInt32(dbReader["cId"].ToString()), dbReader["cName"].ToString());
returnList.Add(c);
}
AccessDBSQLClient.Close();
return returnList;
}
public static List<Customer> GetCustomersByEmail(string email)
{
List<Customer> returnList = new List<Customer>();
string sql = "select * from Customer where cEmail = '" + email+"'";
dbCmd = AccessDBSQLClient.GetDbCommand(sql);
IDataReader dbReader;
dbReader = dbCmd.ExecuteReader();
Customer c;
while (dbReader.Read())
{
c = new Customer(Convert.ToInt32(dbReader["cId"].ToString()), dbReader["cName"].ToString());
returnList.Add(c);
}
AccessDBSQLClient.Close();
return returnList;
}
public static List<Subscription> GetCustomerSubscriptions(int cId)
{
List<Subscription> returnList = new List<Subscription>();
string sql = "select S.sId, ST.stName,CM.cmDescription "
+ "from Customer C, Subscription S, SubscriptionType ST, CarModel CM "
+ "where C.cId = S.cId "
+ "and S.stId = ST.stId "
+ "and S.cmId = CM.cmId "
+ "and C.cId = " + cId;
dbCmd = AccessDBSQLClient.GetDbCommand(sql);
IDataReader dbReader;
dbReader = dbCmd.ExecuteReader();
Subscription s;
while (dbReader.Read())
{
//s = new Subscription();
s = new Subscription((int)(dbReader["sId"]).ToString(),
dbReader["stName"],
dbReader["cmDescription"]);
returnList.Add(s);
}
AccessDBSQLClient.Close();
return returnList;
}
Obviously the GetCustomers and GetCustomersByEmail methods are working, but I have no idea how to make the GetCustomerSubscriptions method, as it has to return data fra 2 classes, and I cant just build a Customer to add to the resultset.

Related

C# LINQ to SQL Invalid Object Name

public class AMCOMDB : DataContext
{
public Table<student> allStudents;
public Table<aClass> allClasses;
public AMCOMDB(string connection) : base(connection) { }
}
[Table(Name = "student")]
public class student
{
private string _studentName;
[Column(IsPrimaryKey =true,Storage ="_studentName")]
public string studentName
{
get { return this._studentName; }
set { this._studentName = value; }
}
private string _LARType;
[Column(Storage ="_LARType")]
public string LARType
{
get { return this._LARType; }
set { this._LARType = value; }
}
private string _studentType;
[Column(Storage = "_studentType")]
public string studentType
{
get { return this._studentType; }
set { this._studentType = value; }
}
private string _aviationLevel;
[Column(Storage = "_aviationLevel")]
public string aviationLevel
{
get { return this._aviationLevel; }
set { this._aviationLevel = value; }
}
private string _airDefenseLevel;
[Column(Storage = "_airDefenseLevel")]
public string airDefenseLevel
{
get
{
return this._airDefenseLevel;
}
set
{
this._airDefenseLevel = value;
}
}
private string _emergencyContact;
[Column(Storage = "_emergencyContact")]
public string emergencyContact
{
get
{
return this._emergencyContact;
}
set
{
this._emergencyContact = value;
}
}
[Table(Name = "grades")]
public class grades
{
private string _studentName;
[Column(IsPrimaryKey = true, Storage = "_studentName")]
public string studentName
{
get
{
return this._studentName;
}
set
{
this._studentName = value;
}
}
private int _ET;
[Column(Storage = "_ET")]
public int ET
{
get
{
return this._ET;
}
set
{
this._ET = value;
}
}
private int _CP;
[Column(Storage = "_CP")]
public int CP
{
get
{
return this._CP;
}
set
{
this._CP = value;
}
}
private int _SB;
[Column(Storage = "_SB")]
public int SB
{
get
{
return this._SB;
}
set
{
this._SB = value;
}
}
private int _EC;
[Column(Storage = "_EC")]
public int EC
{
get
{
return this._EC;
}
set
{
this._EC = value;
}
}
private int _finalGrade;
[Column(Storage = "_finalGrade")]
public int finalGrade
{
get
{
return this._finalGrade;
}
set
{
this._finalGrade = value;
}
}
}
[Table(Name = "classes")]
public class aClass
{
private string _classNumber;
[Column(IsPrimaryKey = true, Storage = "_classNumber")]
public string classNumber
{
get
{
return this._classNumber;
}
set
{
this._classNumber = value;
}
}
private string _courseSeries;
[Column(Storage = "_courseSeries")]
public string courseSeries
{
get
{
return this._courseSeries;
}
set
{
this._courseSeries = value;
}
}
private string _courseNumber;
[Column(Storage = "_courseNumber")]
public string courseNumber
{
get
{
return this._courseNumber;
}
set
{
this._courseNumber = value;
}
}
private string _distanceLearning;
[Column(Storage = "_distanceLearning")]
public string distanceLearning
{
get
{
return this._distanceLearning;
}
set
{
this._distanceLearning = value;
}
}
private string _classStartDate;
[Column(Storage = "_classStartDate")]
public string classStartDate
{
get
{
return this._classStartDate;
}
set
{
this._classStartDate = value;
}
}
private string _classEndDate;
[Column(Storage = "_classEndDate")]
public string classEndDate
{
get
{
return this._classEndDate;
}
set
{
this._classEndDate = value;
}
}
private string _primaryInstructor;
[Column(Storage = "_primaryInstructor")]
public string primaryInstructor
{
get
{
return this._primaryInstructor;
}
set
{
this._primaryInstructor = value;
}
}
private string _secondaryInstructor;
[Column(Storage = "_secondaryInstructor")]
public string secondaryInstructor
{
get
{
return this._secondaryInstructor;
}
set
{
this._secondaryInstructor = value;
}
}
private string _location;
[Column(Storage = "_location")]
public string location
{
get
{
return this._location;
}
set
{
this._location = value;
}
}
private string _TDYCosts;
[Column(Storage = "_TDYCosts")]
public string TDYCosts
{
get
{
return this._TDYCosts;
}
set
{
this._TDYCosts = value;
}
}
private string _studentCount;
[Column(Storage = "_studentCount")]
public string studentCount
{
get
{
return this._studentCount;
}
set
{
this._studentCount = value;
}
}
private List<grades> _classGrades;
[Column(Storage = "_classGrades")]
public List<grades> classGrades
{
get
{
return this._classGrades;
}
set
{
this._classGrades = value;
}
}
AMCOMDB ADB = new AMCOMDB(connectionString);
if (ADB.DatabaseExists())
{
var stud = ADB.GetTable<student>();
var clas = ADB.GetTable<aClass>();
IQueryable<string> query = from c in stud
where c.studentName.Length > 5
orderby c.studentName.Length
select c.studentName.ToUpper();
foreach (string name in query)
{
}
//var q = from a in ADB.GetTable<student>()
// select a;
//dtStudents = LinqQuerytoDataTable(q);
//var q1 = from a in ADB.GetTable<aClass>()
// select a;
//aClass c = new aClass();
//dtClasses = reformatDataTable(q1);
}
I receive the following when I try to get information from the database at (foreach (string name in query))
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: Invalid object name 'student'.
I also get this when I first create the database:
An unhandled exception of type 'System.InvalidOperationException' occurred in System.Data.Linq.dll
Additional information: Unable to determine SQL type for 'System.Collections.Generic.List`1[WindowsFormsApplication1.Form1+grades]'.
remove the word Name that is what worked for me
[Table("student")]
public class student

C# How to load data to messagebox

I have:
private void Tab2KsiazkiBTSzczegoly_Click(object sender, EventArgs e)
{
string KodKsiazki;
KodKsiazki = DataWyszukajKsiazki.Rows[DataWyszukajKsiazki.CurrentCell.RowIndex].Cells[2].Value.ToString();
TSzczegolyDb _szczegoly = new TSzczegolyDb();
Global.listSzczegoly = _szczegoly.GetSZCZEGOLY(KodKsiazki);
//StringBuilder sb = new StringBuilder();
//foreach (DataGridViewCell cell in DataWyszukajKsiazki.SelectedCells)
//{
// sb.AppendLine(cell.Value.ToString());
//}
//MessageBox.Show(sb.ToString());
//}
MessageBox.Show(_szczegoly.ToString());
}
class like that:
public class TSzczegolyDb : Core.CoreMSSQL
{
static string connectionString = TconStrDb.GetConectionString();
public TSzczegolyDb()
: base(connectionString)
{
}
public List<TSzczegolyDto> GetSZCZEGOLY(string co)
{
List<TSzczegolyDto> list = null;
list = new List<TSzczegolyDto>();
SqlCommand command = new SqlCommand();
command.CommandText = "SELECT Tytul, Autorzy, ISBN10, ISBN13, IlStron, Wydawnictwo, Gatunek, Opis FROM dbo.TKsiazki WHERE dbo.TKsiazki.KodKsiazki = '" + co + "'";
SqlDataReader reader = ExecuteQuery(command);
while (reader.Read())
{
TSzczegolyDto message = new TSzczegolyDto();
if (!reader.IsDBNull(0))
{
message.Tytuł = reader.GetString(0);
}
if (!reader.IsDBNull(1))
{
message.Autorzy = reader.GetString(1);
}
if (!reader.IsDBNull(2))
{
message.ISBN10 = reader.GetString(2);
}
if (!reader.IsDBNull(3))
{
message.ISBN13 = reader.GetString(3);
}
if (!reader.IsDBNull(4))
{
message.IlStron = reader.GetInt32(4);
}
if (!reader.IsDBNull(5))
{
message.Wydawnictwo = reader.GetString(5);
}
if (!reader.IsDBNull(6))
{
message.Gatunek = reader.GetString(6);
}
if (!reader.IsDBNull(7))
{
message.Opis = reader.GetString(7);
}
list.Add(message);
}
return list;
}
and second:
public class TSzczegolyDto
{
private string _tytul;
public string Tytuł
{
get { return _tytul; }
set { _tytul = value; }
}
private string _autorzy;
public string Autorzy
{
get { return _autorzy; }
set { _autorzy = value; }
}
private string _ISBN10;
public string ISBN10
{
get { return _ISBN10; }
set { _ISBN10 = value; }
}
private string _ISBN13;
public string ISBN13
{
get { return _ISBN13; }
set { _ISBN13 = value; }
}
private long _ilstron;
public long IlStron
{
get { return _ilstron; }
set { _ilstron = value; }
}
private string _wydawnictwo;
public string Wydawnictwo
{
get { return _wydawnictwo; }
set { _wydawnictwo = value; }
}
private string _gatunek;
public string Gatunek
{
get { return _gatunek; }
set { _gatunek = value; }
}
private string _opis;
public string Opis
{
get { return _opis; }
set { _opis = value; }
}
}
I want show _szczegoly on MessageBox but when I try to MessageBox.Show(_szczegoly.ToString()); then is wrong. In _szczegoly I have string and long type data.
How to create messagebox with this data?
I think you are trying to show an Object with a MessageBox, you need to override the ToString() method to show propertly:
class TSzczegolyDb
{
public override string ToString()
{
return this.Property1 + this.Property2 /*....*/;
}
}

C# Inconsistent accessibility error

I am having trouble to fix the errors in my object oriented program in C#. The program has 9 classes and in the one class. The Error is Inconsistent accessibility: parameter type 'Employee.Employee' is less accessible than method 'Employee.EmployeeInput.CollectEmployeeInfo(Employee.Employee)'
on the coding
public static void CollectEmployeeInfo(Employee theEmployee)
{
theEmployee.Firstname = InputUtilities.getStringInputValue("First Name");
theEmployee.Lastname = InputUtilities.getStringInputValue("Last name");
theEmployee.Gender = InputUtilities.getCharInputValue("Gender");
theEmployee.Dependents = InputUtilities.getIntegerInputValue("# Dependents");
}
the CollectEmployeeInfo is what is showing the error and I am not sure what has to be done to the other classes to fix the error. Any help would be greatly appreciated
class Employee
{
public const double MIN_SALARY = 20000;
public const double MAX_SALARY = 100000;
public const int MIN_DEPENDENTS = 0;
public const int MAX_DEPENDENTS = 10;
public const string DEFAULT_NAME = "not given";
public const char DEFAULT_GENDER = 'U';
public const string DEFAULT_TYPE = "Generic Employee";
protected string firstName;
protected string lastName;
protected double annualSalary;
protected char gender;
protected int dependents;
protected static int numEmployees = 0;
protected Benefits employeeBenefits;
protected string employeeType;
public Employee()
{
firstName = DEFAULT_NAME;
lastName = DEFAULT_NAME;
annualSalary = MIN_SALARY;
dependents = MIN_DEPENDENTS;
numEmployees++;
employeeBenefits = new Benefits();
}
public Employee(string firstname, string lastname, char gender, int dependents, double annualsalary, Benefits employeeBenefits)
{
Firstname = firstname;
Lastname = lastname;
AnnualSalary = annualsalary;
Gender = gender;
Dependents = dependents;
EmployeeBenefits = employeeBenefits;
numEmployees++;
}
public Benefits EmployeeBenefits
{
get { return employeeBenefits; }
set
{
if (value == null)
employeeBenefits = new Benefits();
else
employeeBenefits = value;
}
}
public Employee(string employeeType)
: this()
{
EmployeeType = employeeType;
}
public string Firstname
{
get { return firstName; }
set
{
if (String.IsNullOrEmpty(value))
firstName = DEFAULT_NAME;
else
firstName = value;
}
}
public string Lastname
{
get { return lastName; }
set
{
if (String.IsNullOrEmpty(value))
lastName = DEFAULT_NAME;
else
lastName = value;
}
}
public double AnnualSalary
{
get { return annualSalary; }
set
{
if (value > MIN_SALARY & value < MAX_SALARY)
annualSalary = value;
else if (value < MIN_SALARY)
annualSalary = MIN_SALARY;
else
annualSalary = MAX_SALARY;
}
}
public char Gender
{
get { return gender; }
set
{
if (value == 'F')
gender = value;
else if (value == 'f')
gender = value;
else if (value == 'M')
gender = value;
else if (value == 'm')
gender = value;
else
gender = DEFAULT_GENDER;
}
}
public int Dependents
{
get { return dependents; }
set
{
if (value >= MIN_DEPENDENTS & value <= MAX_DEPENDENTS)
dependents = value;
else if (value < MIN_DEPENDENTS)
dependents = MIN_DEPENDENTS;
else
dependents = MAX_DEPENDENTS;
}
}
public static int NumEmployees
{
get { return numEmployees; }
}
public string EmployeeName
{
get { return firstName + " " + lastName; }
}
public string EmployeeType
{
get { return employeeType; }
set
{
if (String.IsNullOrEmpty(value))
employeeType = DEFAULT_TYPE;
else
employeeType = value;
}
}
public double CalculatePay()
{
return annualSalary / 52;
}
public double CalculatePay(double modifiedSalary)
{
AnnualSalary = modifiedSalary;
return AnnualSalary / 52;
}
public override string ToString()
{
string output;
output = "\n============ Employee Information ============";
output += "\n\t Type:\t" + employeeType;
output += "\n\t Name:\t" + firstName + " " + lastName;
output += "\n\t Gender:\t" + gender;
output += "\n\t Dependents:\t" + dependents;
output += "\n\tAnnual Salary:\t" + annualSalary.ToString("C2");
output += "\n\t Weekly Pay:\t" + CalculatePay().ToString("C2");
output += "\n\t" + employeeBenefits.ToString();
return output;
}
}
}
Employee type should be not less accessible than CollectEmployeeInfo.
So Employee should be defined as public "at least"
All of the types you need to pass to a method must be at least as accessible as that method. If Employee is a private or internal class it can't be passed to this method from outside that class/assembly.
Make Employee public and it should work.

How do I populate the data from my Stored Procedure into my winform?

I'm pretty new to programming and have run into a problem with a basic application I am working on. I have a person class which resembles this...
Person
{
SqlConnection conn = new SqlConnection(#"Integrated Security=True; Data
Source=ME\MyPRESS;Initial Catalog=TEST5");
SqlCommand cmd = new SqlCommand("usp_employee", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#emp_id", SqlDbType.Int).Value = id;
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
try
{
conn.Open();
{
department = dr["dept_name"].ToString();
fname = dr["emp_first_name"].ToString();
lname = dr["emp_last_name"].ToString();
email = dr["emp_email"].ToString();
phone = dr["emp_phone"].ToString();
position = dr["emp_position"].ToString();
address1 = dr["emp_address1"].ToString();
address2 = dr["emp_address2"].ToString();
city = dr["emp_city"].ToString();
state = dr["emp_state"].ToString();
postal_code = dr["emp_postal_code"].ToString();
// department = txtFirst_name.Text;
}
}
finally
{
// 3. close the reader
if (dr != null)
{
dr.Close();
}
// close the connection
if (conn != null)
{
conn.Close();
}
}
}
protected string department;
public string Department
{
get { return department; }
set { department = value; }
}
protected string fname;
public string Fname
{
get { return fname; }
set { fname = value;}
}
protected string lname;
public string Lname
{
get { return lname; }
set { lname = value; }
}
protected string email;
public string Email
{
get { return email; }
set { email = value; }
}
protected string position;
public string Position
{
get { return position; }
set { position = value; }
}
protected string address1;
public string Address1
{
get { return address1; }
set { address1 = value; }
}
protected string address2;
public string Address2
{
get { return address2; }
set { address2 = value; }
}
protected string phone;
public string Phone
{
get { return phone; }
set { phone = value; }
}
protected string city;
public string City
{
get { return city; }
set { city = value; }
}
protected string state;
public string State
{
get { return state; }
set { state = value; }
}
protected string postal_code;
public string Postal_Code
{
get { return postal_code; }
set { postal_code = value; }
}
}
I have a form and a db with a stored procedure to retrieve the data as you can see above....
Where I am lost is in wiring up my form to display the record from the stored procedure.
A simple way would be to define a constructor for your Person class:
public class Person
{
public Person(string Department, string fName /* etc */)
{
this.Department = Department;
this.fName = fName;
// and so on for all the fields
}
// the rest of the class definition goes here
}
Then when looping through the data, create a Person object using that constructor. Return the new Person object from your function.
That helps! I have it up and running now....
public Person(int id)
{
SqlConnection conn = new SqlConnection(#"Integrated Security=True; Data Source=JODIEPC\XPRESS;Initial Catalog=TEST5");
conn.Open();
SqlCommand cmd = new SqlCommand("usp_EmployeeSelect", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#emp_id", SqlDbType.Int).Value = id;
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
department = dr["dept_name"].ToString();
fname = dr["emp_first_name"].ToString();
lname = dr["emp_last_name"].ToString();
email = dr["emp_email"].ToString();
phone = dr["emp_phone"].ToString();
position = dr["emp_position"].ToString();
address1 = dr["emp_address1"].ToString();
address2 = dr["emp_address2"].ToString();
city = dr["emp_city"].ToString();
state = dr["emp_state"].ToString();
postal_code = dr["emp_postal_code"].ToString();
}
}
protected int id;
protected string fname;
protected string lname;
protected string department;
protected string email;
protected string position;
protected string address1;
protected string address2;
protected string phone;
protected string city;
protected string state;
protected string postal_code;
public int Id
{
get { return id; }
set { id = value; }
}
public string Department
{
get { return department; }
set{ department = value; }
}
public string Fname
{
get { return fname; }
set { fname = value; }
}
public string Lname
{
get { return lname; }
set { lname = value; }
}
public string Email
{
get { return email; }
set { email = value; }
}
public string Position
{
get { return position; }
set { position = value; }
}
public string Address1
{
get { return address1; }
set { address1 = value; }
}
public string Address2
{
get { return address2; }
set { address2 = value; }
}
public string Phone
{
get { return phone; }
set { phone = value; }
}
public string City
{
get { return city; }
set { city = value; }
}
public string State
{
get { return state; }
set { state = value; }
}
public string Postal_Code
{
get { return postal_code; }
set { postal_code = value; }
}
}
---------winform---------------
private void btnSearch_Click(object sender, EventArgs e)
{
Person Emp = new Person(Int32.Parse(txtId.Text));
txtFirstName.Text = Emp.Fname;
txtLastName.Text = Emp.Lname;
txtEmail.Text = Emp.Fname;
txtPhone.Text = Emp.Phone;
txtDepartment.Text = Emp.Department;
txtPosition.Text = Emp.Position;
txtAddress1.Text = Emp.Address1;
txtAddress2.Text =Emp.Address2;
txtCity.Text = Emp.City;
txtState.Text = Emp.State;
txtPostalCode.Text = Emp.Postal_Code;
}
}
It's not the most creative way of going about it but it works....
Thanks alot guys....

Getting object reference not set to an instance of object for Business layer code attached

I have this Business Layer/ Contactentry.ascx page which calls a stored prcoedure to insert data into sql database and then the page below calls this business layer method. the issue is this method
aspdotnet.BusinessLogicLayer.ContactEntry AddEntry =
new ContactEntry(Convert.ToInt32(Session["ContactID"].ToString())
,Title,FirstName,MiddleName,LastName,JobTitle,Company,Website,OfficePhone
,HomePhone,Mobile,Fax,OEmail,PEmail,OAStreet,OACity,OAState,OACountry
,OAZipCode,PAStreet,PACity,PAState,PACountry,PAZipCode);
throws an error saying object refernece not set to an instance of an object although I have entered all values for the text fields.
using System;
using System.Data;
using System.Configuration;
using aspdotnet.DataAccessLayer;
namespace aspdotnet.BusinessLogicLayer
{
public class ContactEntry
{
private int _ContactID;
private string _Title;
private string _FirstName;
private string _MiddleName;
private string _LastName;
private string _JobTitle;
private string _Company;
private string _Website;
private string _OfficePhone;
private string _HomePhone;
private string _Mobile;
private string _Fax;
private string _OEmail;
private string _PEmail;
private string _OAStreet;
private string _OACity;
private string _OAState;
private string _OACountry;
private string _OAZipCode;
private string _PAStreet;
private string _PACity;
private string _PAState;
private string _PACountry;
private string _PAZipCode;
public int ContactID
{
get { return _ContactID; }
set { _ContactID = value; }
}
public string Title
{
get { return _Title; }
set { _Title = value; }
}
public string FirstName
{
get { return _FirstName; }
set { _FirstName = value; }
}
public string MiddleName
{
get { return _MiddleName; }
set { _MiddleName = value; }
}
public string LastName
{
get { return _LastName; }
set { _LastName = value; }
}
public string JobTitle
{
get { return _JobTitle; }
set { _JobTitle = value; }
}
public string Company
{
get { return _Company; }
set { _Company = value; }
}
public string Website
{
get { return _Website; }
set { _Website = value; }
}
public string OfficePhone
{
get { return _OfficePhone; }
set { _OfficePhone = value; }
}
public string HomePhone
{
get { return _HomePhone; }
set { _HomePhone = value; }
}
public string Mobile
{
get { return _Mobile; }
set { _Mobile = value; }
}
public string Fax
{
get { return _Fax; }
set { _Fax = value; }
}
public string OEmail
{
get { return _OEmail; }
set { _OEmail = value; }
}
public string PEmail
{
get { return _PEmail; }
set { _PEmail = value; }
}
public string OAStreet
{
get { return _OAStreet; }
set { _OAStreet = value; }
}
public string OACity
{
get { return _OACity; }
set { _OACity = value; }
}
public string OAState
{
get { return _OAState; }
set { _OAState = value; }
}
public string OACountry
{
get { return _OACountry; }
set { _OACountry = value; }
}
public string OAZipCode
{
get { return _OAZipCode; }
set { _OAZipCode = value; }
}
public string PAStreet
{
get { return _PAStreet; }
set { _PAStreet = value; }
}
public string PACity
{
get { return _PACity; }
set { _PACity = value; }
}
public string PAState
{
get { return _PAState; }
set { _PAState = value; }
}
public string PACountry
{
get { return _PACountry; }
set { _PACountry = value; }
}
public string PAZipCode
{
get { return _PAZipCode; }
set { _PAZipCode = value; }
}
public ContactEntry()
{
}
public ContactEntry(int ContactID, string Title, string FirstName, string MiddleName, string LastName, string JobTitle, string Company, string Website, string OfficePhone, string HomePhone, string Mobile, string Fax, string OEmail, string PEmail, string OAStreet, string OACity, string OAState, string OACountry, string OAZipCode, string PAStreet, string PACity, string PAState, string PACountry, string PAZipCode)
{
_ContactID=ContactID;
_Title=Title;
_FirstName = FirstName;
_MiddleName = MiddleName;
_LastName = LastName;
_JobTitle = JobTitle;
_Company = Company;
_Website = Website;
_OfficePhone = OfficePhone;
_HomePhone = HomePhone;
_Mobile = Mobile;
_Fax = Fax;
_OEmail=OEmail;
_PEmail=PEmail;
_OAStreet = OAStreet;
_OACity = OACity;
_OAState = OAState;
_OACountry =OACountry;
_OAZipCode = OAZipCode;
_PAStreet = PAStreet;
_PACity = PACity;
_PAState = PAState;
_PACountry = PACountry;
_PAZipCode = PAZipCode;
}
public bool Save()
{
if (_ContactID == 0)
return Insert();
else
return Update();
}
private bool Insert()
{
_ContactID = Convert.ToInt32(DBTask.ExecuteScalar(System.Configuration.ConfigurationManager.AppSettings[Web.Global.CfgKeyConnString], "ContactInfo_Insert", _Title, _FirstName, _MiddleName, _LastName, _JobTitle, _Company, _Website, _OfficePhone, _HomePhone, _Mobile, _Fax, _OEmail, _PEmail, _OAStreet, _OACity, _OAState, _OACountry, _OAZipCode, _PAStreet, _PACity, _PAState, _PACountry, _PAZipCode));
return (0 < _ContactID);
}
public static void Remove(int ContactID)
{
DBTask.ExecuteNonQuery(System.Configuration.ConfigurationManager.AppSettings[Web.Global.CfgKeyConnString], "ContactInfo_Delete", ContactID);
}
private bool Update()
{
try
{
DBTask.ExecuteNonQuery(System.Configuration.ConfigurationManager.AppSettings[Web.Global.CfgKeyConnString], "ContactInfo_Update", _ContactID, _Title, _FirstName, _MiddleName, _LastName, _JobTitle, _Company, _Website, _OfficePhone, _HomePhone, _Mobile, _Fax, _OEmail, _PEmail, _OAStreet, _OACity, _OAState, _OACountry, _OAZipCode, _PAStreet, _PACity, _PAState, _PACountry, _PAZipCode);
return true;
}
catch
{
return false;
}
}
public void LoadContact(int ContactID)
{
DataSet ds = DBTask.ExecuteDataset(System.Configuration.ConfigurationManager.AppSettings[Web.Global.CfgKeyConnString], "ContactInfo_GetContact", ContactID);
DataRow row = ds.Tables[0].Rows[0];
_ContactID=Convert.ToInt32(row["ContactID"].ToString());
_Title=row["Title"].ToString();
_FirstName = row["FirstName"].ToString();
_MiddleName = row["MiddleName"].ToString();
_LastName = row["LastName"].ToString();
_JobTitle = row["JobTitle"].ToString();
_Company = row["Company"].ToString();
_Website = row["Website"].ToString();
_OfficePhone = row["OfficePhone"].ToString();
_HomePhone = row["HomePhone"].ToString();
_Mobile = row["Mobile"].ToString();
_Fax = row["Fax"].ToString();
_OEmail=row["OfficialEmail"].ToString();
_PEmail=row["PersonalEmail"].ToString();
_OAStreet = row["OAStreet"].ToString();
_OACity = row["OACity"].ToString();
_OAState = row["OAState"].ToString();
_OACountry =row["OACountry"].ToString();
_OAZipCode = row["OAZip"].ToString();
_PAStreet = row["PAStreet"].ToString();
_PACity = row["PACity"].ToString();
_PAState = row["PAState"].ToString();
_PACountry = row["PACountry"].ToString();
_PAZipCode = row["PAZip"].ToString();
}
}
}
Insert form calling above function from Business Layer:
private void btnSave_Click(object sender, System.EventArgs e)
{
string Title = drplstTitle.SelectedItem.Text;
string FirstName = txtFirstName.Text;
string MiddleName = txtMiddleName.Text;
string LastName = txtLastName.Text;
string JobTitle = this.txtJobTitle.Text;
string Company = this.txtCompany.Text;
string Website = this.txtWebSite.Text;
string OfficePhone = this.txtOfficePhone.Text;
string HomePhone = this.txtHomePhone.Text;
string Mobile = this.txtMobile.Text;
string Fax = this.txtFax.Text;
string OEmail = this.txtOfficialEmail.Text;
string PEmail = this.txtPersonalEmail.Text;
string OAStreet = this.txtOAStreet.Text;
string OACity = this.txtOACity.Text ;
string OAState = this.txtOAState.Text;
string OACountry = this.txtOACountry.Text;
string OAZipCode = this.txtOAZipCode.Text;
string PAStreet = this.txtPAStreet.Text;
string PACity = this.txtPACity.Text;
string PAState = this.txtPAState.Text;
string PACountry = this.txtPACountry.Text;
string PAZipCode = this.txtPAZipCode.Text;
aspdotnet.BusinessLogicLayer.ContactEntry AddEntry =
new ContactEntry(Convert.ToInt32(Session["ContactID"].ToString()),Title,FirstName,MiddleName,LastName,JobTitle,Company,Website,OfficePhone,HomePhone,Mobile,Fax,OEmail,PEmail,OAStreet,OACity,OAState,OACountry,OAZipCode,PAStreet,PACity,PAState,PACountry,PAZipCode);
//AddEntry.Save();
}
I get object reference not set to an insance of object right after above method aspdotnet.BusinessLogicLayer.ContactEntry above. I see all values are being passed when I am debugging. I entered all values when entering values above but it still errors out. Not sure what I am missing. Please help , appreciate your time.
This line is suspicious:
Convert.ToInt32(Session["ContactID"].ToString())
Session["ContactID"] may return null and calling ToString() on null blows up. Convert.ToInt32(null) wouldn't throw an error - it would return 0, not NULL.
You to handle Session["ContactID"] for nulls and Empty before Converting it to Int32
Example :
ContactEntry cEntry = null;
if(Session["ContactID"] != null)
{
if(!String.IsNullOrEmpty(Session["ContactID"]))
{
cEntry = new ContactEntry(Convert.ToInt32(Session["ContactID"].ToString());
}
}
Check your Session["ContactID"].
Consider changing your code to something like this...
//...
string PAState = this.txtPAState.Text;
string PACountry = this.txtPACountry.Text;
string PAZipCode = this.txtPAZipCode.Text;
string contactIDstr = Session["ContactID"] as string;
int contactID = 0;
if(!String.IsNullOrEmpty(conactIDStr))
Int32.TryParse(contactIDStr, out contactID);
aspdotnet.BusinessLogicLayer.ContactEntry AddEntry = new ContactEntry(
contentID,
Title,
FirstName,MiddleName,LastName,JobTitle,Company,
Website,OfficePhone,HomePhone,Mobile,Fax,OEmail,PEmail,
OAStreet,OACity,OAState,OACountry,OAZipCode,PAStreet,PACity,PAState,PACountry,PAZipCode
);

Categories

Resources