I am having an issue with my code today. Whenever I use this method to add a Product to my local DB, it throws an exception that reads "Object cannot be cast from DBNull to other types". After doing some research, I believe my issue resides with the insertCmd parameters in the AddProduct method, but I cannot seem to figure out exactly what is causing it. The program that I have created still functions correctly (it adds the product and can then be selected successfully), however it just seems to keep throwing this exception when I add the product.
Can anyone provide any insight as to where the issue might lie within my code? If you need any more information, please do not hesitate to ask. Thank you for your time and help.
public static bool AddProduct(Product product)
{
SqlConnection connect = MMABooksDB.GetConnection();
string insert = "INSERT Products " + "(ProductCode, Description, UnitPrice) " + "VALUES (#code, #description, #price)";
SqlCommand insertCmd = new SqlCommand(insert, connect);
insertCmd.Parameters.AddWithValue("#code", product.code);
insertCmd.Parameters.AddWithValue("#description", product.description);
insertCmd.Parameters.AddWithValue("#price", product.price);
try
{
connect.Open();
insertCmd.ExecuteNonQuery();
string selectStatement =
"SELECT IDENT_CURRENT('Products') FROM Products";
SqlCommand selectCommand = new SqlCommand(selectStatement, connect);
int ProductCode = Convert.ToInt32(selectCommand.ExecuteScalar());
return true;
}
catch (SqlException ex)
{
throw ex;
}
finally
{
connect.Close();
}
}
And here is the product class
public class Product
{
public string code;
public string description;
public decimal price;
public Product() { }
public Product(string code, string description, decimal price)
{
this.Code = code;
this.Description = description;
this.Price = price;
}
public string Code
{
get
{
return code;
}
set
{
code = value;
}
}
public string Description
{
get
{
return description;
}
set
{
description = value;
}
}
public decimal Price
{
get
{
return price;
}
set
{
price = value;
}
}
public string GetDisplayText()
{
return code + ", " + price.ToString("c") + ", " + description;
}
public string GetDisplayText(string sep)
{
return code + sep + price.ToString("c") + sep + description;
}
}
int ProductCode; //declare variable
object dbProductID = selectCommand.ExecuteScalar(); //get the result into object
if(dbProductID !=null || dbProductID != DBNull.Value) //check if it is null
ProductCode = 0; //assign some default value here if it has no productid
else
ProductCode = Convert.ToInt32(dbProductID);//if its has productid cast it into int
if the product is getting added I would assume the cannot convert is coming from int ProductCode = Convert.ToInt32(selectCommand.ExecuteScalar()); I would add a check to see if that scaler is returning null.
Related
i have ran into some problems with my insert function.
i am trying to make my the string listing_ID an auto increment int with no input needed, however when coding for the button submit i included all the inputs for all the other values but not listing_ID , this gave me the error below. below are all the images and these are the codes for the insert function.
public class Carlisting
{
private string _listID = "";
private string _car_model = "";
private string _brand_name = "";
private string _car_description = "";
private string _car_condition = "";
private string _price = "";
private string _inspection_date = "";
string _connStr = ConfigurationManager.ConnectionStrings["roadbnb.mdf"].ConnectionString;
public Carlisting(string listID, string car_model, string brand_name, string car_description, string car_condition, string price, string inspection_date)
{
_listID = listID;
_car_model = car_model;
_brand_name = brand_name;
_car_description = car_description;
_car_condition = car_condition;
_price = price;
_inspection_date = inspection_date;
}
public Carlisting()
{
}
public string listing_ID
{
get { return _listID; }
set { _listID = value; }
}
public string car_model
{
get { return _car_model; }
set { _brand_name = value; }
}
public string brand_name
{
get { return _brand_name; }
set { _brand_name = value; }
}
public string car_description
{
get { return _car_description; }
set { _car_description = value; }
}
public string car_condition
{
get { return _car_condition; }
set { _car_condition = value; }
}
public string price
{
get { return _price; }
set { _price = value; }
}
public string inspection_date
{
get { return _inspection_date; }
set { _inspection_date = value; }
}
protected void btn_submit_Click(object sender, EventArgs e)
{
int result = 0;
Carlisting car = new Carlisting(tb_model.Text, tb_brand.Text, tb_description.Text, dl_condition.Text, tb_price.Text, tb_date.Text);
result = car.ListingInsert();
if (result > 0)
{
Response.Write("<script>alert('You have succesfully added listing , PLease wait for approval');</script>");
}
else
{
Response.Write("<script>alert('Error : PLease contact helpdesk');</script>");
}
}
public int ListingInsert()
{
int result = 0;
string queryStr = "INSERT INTO Carlisting(car_model, brand_name, car_description, car_condition , price, inspection_date)"
+"VALUES (#car_model, #brand_name, #car_description, #car_condition, #price, #inspection_date)";
SqlConnection conn = new SqlConnection(_connStr);
SqlCommand cmd = new SqlCommand(queryStr, conn);
cmd.Parameters.AddWithValue("#car_model", this.car_model);
cmd.Parameters.AddWithValue("#brand_Name", this.brand_name);
cmd.Parameters.AddWithValue("#car_description", this.car_description);
cmd.Parameters.AddWithValue("#car_condition", this.car_condition);
cmd.Parameters.AddWithValue("#price", this.price);
cmd.Parameters.AddWithValue("#inspection_date", this.inspection_date);
conn.Open();
result += cmd.ExecuteNonQuery();
conn.Close();
return result;
}
Does anyone know how should fix it in order to get the results i wan? Thank you in advance
As per your screenshot, you are getting compilation error. To Fix it, create another constructor. Currently your code want to invoke constructor which does not take listId as parameter.
public Carlisting(string listID, string car_model, string brand_name, string car_description, string car_condition, string price, string inspection_date)
: this(car_model, brand_name, car_description, car_condition, price, inspection_date)
{
_listID = listID;
}
public Carlisting(string car_model, string brand_name, string car_description, string car_condition, string price, string inspection_date)
{
_car_model = car_model;
_brand_name = brand_name;
_car_description = car_description;
_car_condition = car_condition;
_price = price;
_inspection_date = inspection_date;
}
With above the 1st constructor invokes the another constructor with other required parameters. And for your code, the 2nd constructor will be invoked and you won't have compilation error.
I am consuming wcf service into console application . I am trying to retrieve account information based on account number . But the problem is when i enter the account number and hit enter ,its only displaying account number and rest of the fields are empty.
Here is the base class.
[DataContract]
public class Current_Account_Details
{
string account_creation_date;
string account_type;
string branch_sort_code;
string account_fees;
string account_balance;
string over_draft_limit;
string account_holder_id;
[DataMember]
public string Account_Creation_Date
{
get { return account_creation_date; }
set { account_creation_date = value; }
}
[DataMember]
public string Account_Type
{
get { return account_type; }
set { account_type = value; }
}
[DataMember]
public string Branch_Sort_Code
{
get { return branch_sort_code; }
set { branch_sort_code = value; }
}
[DataMember]
public string Account_Fees
{
get { return account_fees; }
set { account_fees = value; }
}
[DataMember]
public string Account_Balance
{
get { return account_balance; }
set { account_balance = value; }
}
[DataMember]
public string Over_Draft_Limit
{
get { return over_draft_limit; }
set { over_draft_limit = value; }
}
[DataMember]
public string Account_Holder_Id
{
get { return account_holder_id; }
set { account_holder_id = value; }
}
}
}
Here is the inherited class.
[DataContract]
public class AccountBalanceRequest : Current_Account_Details
{
string account_number;
[DataMember]
public string Account_Number
{
get { return account_number; }
set { account_number = value; }
}
}
}
Here is the Interface .
[OperationContract]
AccountBalanceRequest AccountBalanceCheek(AccountBalanceRequest accountNumber);
Here is my Method .
public AccountBalanceRequest AccountBalanceCheek(AccountBalanceRequest accountNumber)
{
using (SqlConnection conn = new SqlConnection(ConnectionString))
{
conn.Open();
//use top 1 since you are only getting one record.
//let us use string interpolation, if you are working below C#6
//replace it with your previous value
var cmd = new SqlCommand($#"SELECT TOP 1
*
FROM
Current_Account_Details
WHERE
Account_Number ='{accountNumber.Account_Number}'", conn);
cmd.CommandType = CommandType.Text;
//use ExecuteReader to execute sql select
//ExecuteNonQuery is for update, delete, and insert.
var reader = cmd.ExecuteReader();
//read the result of the execute command.
while (reader.Read())
{
//assuming that your property is the same as your table schema. refer to your table schema Current_Account_Details
//assuming that your datatype are string... just do the conversion...
accountNumber.Account_Balance = reader["Account_Balance"].ToString();
accountNumber.Account_Fees = reader["Account_Fees"].ToString();
accountNumber.Account_Balance = reader["Account_Balance"].ToString();
accountNumber.Over_Draft_Limit = reader["Over_Draft_Limit"].ToString();
}
return accountNumber;
}
}
Here is the code in Console Application .
public static void Balance()
{
MyService.HalifaxCurrentAccountServiceClient currentAccount = new MyService.HalifaxCurrentAccountServiceClient("NetTcpBinding_IHalifaxCurrentAccountService");
MyService.AccountBalanceRequest cs = new MyService.AccountBalanceRequest();
string AccountNumber;
Console.WriteLine("\nEnter your Account Number--------:");
AccountNumber = Console.ReadLine();
cs.Account_Number = AccountNumber;
// MyService.AccountBalanceRequest cs1 = currentAccount.AccountBalanceCheek(AccountNumber);
MyService.AccountBalanceRequest AccountBalance = currentAccount.AccountBalanceCheek(cs);//error on this line
Console.WriteLine("Account Number is :" + cs.Account_Number);
Console.WriteLine("Account creation date :" + cs.Account_Creation_Date);
Console.WriteLine("Account Type :" + cs.Account_Type);
Console.WriteLine("Branch_Sort_Code:" + cs.Branch_Sort_Code);
Console.WriteLine("Account_Fee:" + cs.Account_Fees);
Console.WriteLine("Account Account_Balance :" + cs.Account_Balance);
Console.WriteLine("Account Over Draft Limit :" + cs.Over_Draft_Limit);
Console.Write("--------------------------");
Console.ReadLine();
//Console.Clear();
}
Here is the screen shot of the database.click here to record
Here is the screen shot when i run the applicationClick here to see the result.In this screen shot only the account number is displaying and rest of the fields are empty
your Current_Account_Details is the base class and AccountBalanceRequest is derived class from your question posted.
If we have classes related by inheritance, the wcf service generally accepts and returns the base type. If you expect the service to accept and return inherited types, then use KnownType attribute.
So its enough if you decorate the base class with contracts and try.
[KnownType(typeof(AccountBalanceRequest))]
[DataContract]
public class Current_Account_Details
{
string account_creation_date;
string account_type;
string branch_sort_code;
string account_fees;
string account_balance;
string over_draft_limit;
string account_holder_id;
[DataMember]
public string Account_Creation_Date
{
get { return account_creation_date; }
set { account_creation_date = value; }
}
[DataMember]
public string Account_Type
{
get { return account_type; }
set { account_type = value; }
}
[DataMember]
public string Branch_Sort_Code
{
get { return branch_sort_code; }
set { branch_sort_code = value; }
}
[DataMember]
public string Account_Fees
{
get { return account_fees; }
set { account_fees = value; }
}
[DataMember]
public string Account_Balance
{
get { return account_balance; }
set { account_balance = value; }
}
[DataMember]
public string Over_Draft_Limit
{
get { return over_draft_limit; }
set { over_draft_limit = value; }
}
[DataMember]
public string Account_Holder_Id
{
get { return account_holder_id; }
set { account_holder_id = value; }
}
}
}
public class AccountBalanceRequest : Current_Account_Details
{
string account_number;
public string Account_Number
{
get { return account_number; }
set { account_number = value; }
}
}
Just check whether account number that you read from console is passed in the accountnumber variable.
var cmd = new SqlCommand("SELECT * FROM Current_Account_Details WHERE Account_Number = '" + accountNumber + "'", conn);
Edit 1: Your service is failing to retrieve records because you are passing the AccountBalanceRequest object and the changes made to the object is not reflected outside the method.
MyService.AccountBalanceRequest cs = new MyService.AccountBalanceRequest();
Change it to.
public AccountBalanceRequest AccountBalanceCheek(AccountBalanceRequest accountNumber)
{
using (SqlConnection conn = new SqlConnection(ConnectionString))
{
conn.Open();
//use top 1 since you are only getting one record.
//let us use string interpolation, if you are working below C#6
//replace it with your previous value
var cmd = new SqlCommand($#"SELECT TOP 1
*
FROM
Current_Account_Details
WHERE
Account_Number ='{accountNumber.Account_Number}'", conn));
cmd.CommandType = CommandType.Text;
//use ExecuteReader to execute sql select
//ExecuteNonQuery is for update, delete, and insert.
var reader = cmd.ExecuteReader();
//read the result of the execute command.
while(reader.Read())
{
//assuming that your property is the same as your table schema. refer to your table schema Current_Account_Details
//assuming that your datatype are string... just do the conversion...
accountNumber.Account_Balance = reader["Account_Balance"].ToString();
accountNumber.Account_Fee = reader["Account_Fee"].ToString();
accountNumber.Account_Balance = reader["Account_Balance"].ToString();
accountNumber.Over_Draft_Limit = reader["Over_Draft_Limit"].ToString();
}
return accountNumber;
}
}
In your console retrieve it,
MyService.AccountBalanceRequest AccountBalance =currentAccount.AccountBalanceCheek(cs);
Console.WriteLine("Your Account Number is :" + cs.Account_Number)
...
I think your problem is that you're passing a reference to the WCF service method and changing it there instead of returning. The documentation says that:
Each operation has a return value and a parameter, even if these are void. However, unlike a local method, in which you can pass references to objects from one object to another, service operations do not pass references to objects. Instead, they pass copies of the objects.
Try to change your code so the method returns the changed object. At the end of AccountBalanceCheek method instead of returning true return accountNumber.
And then in Balance method - remove if statement and change to:
....
cs = currentAccount.AccountBalanceCheek(cs);
Console.WriteLine("Your Account Number is :" + cs.Account_Number);
Console.WriteLine("Your Account Type :" + cs.Account_Balance);
....
To read more about it: Is it possible to pass parameters by reference with WCF
I'm creating a program that adds/edits/deletes products from a database.
Everything else works great, but whenever I try to add a new product (testing with '1234'), I get a primary key violation error.
Violation of PRIMARY KEY constraint 'PK_Products'. Cannot insert
duplicate key in object 'dbo.Products'. The duplicate key value is
(1234 ). The statement has been terminated.
This product number most definitely does not already exist, and still doesn't exist when I search for it afterwards.
Can anyone help me figure out what may be causing this? I am not able to pinpoint the issue.
This is my AddProduct method.
public static bool AddProduct(Product product)
{
SqlConnection connect = MMABooksDB.GetConnection();
string insert = "INSERT Products (ProductCode, Description, UnitPrice) VALUES (#code, #description, #price)";
SqlCommand insertCmd = new SqlCommand(insert, connect);
insertCmd.Parameters.AddWithValue("#code", product.Code);
insertCmd.Parameters.AddWithValue("#description", product.Description);
insertCmd.Parameters.AddWithValue("#price", product.Price);
try
{
connect.Open();
int counter = insertCmd.ExecuteNonQuery();
string selectStatement =
"SELECT IDENT_CURRENT('Products') FROM Products";
SqlCommand selectCommand = new SqlCommand(selectStatement, connect);
int ProductCode;
object dbProductID = selectCommand.ExecuteScalar();
if (dbProductID != null || dbProductID != DBNull.Value)
ProductCode = 0;
else
ProductCode = Convert.ToInt32(dbProductID);
if (counter>0)
return true;
else
return false;
}
catch (SqlException ex)
{
throw ex;
}
finally
{
connect.Close();
}
}
And this is the Product class
public class Product
{
public string code;
public string description;
public decimal price;
public Product() { }
public Product(string code, string description, decimal price)
{
this.Code = code;
this.Description = description;
this.Price = price;
}
public string Code
{
get
{
return code;
}
set
{
code = value;
}
}
public string Description
{
get
{
return description;
}
set
{
description = value;
}
}
public decimal Price
{
get
{
return price;
}
set
{
price = value;
}
}
public string GetDisplayText()
{
return code + ", " + price.ToString("c") + ", " + description;
}
public string GetDisplayText(string sep)
{
return code + sep + price.ToString("c") + sep + description;
}
}
}
You guys have already helped me with this program once tonight, and I am very grateful. Thank you for any insight you can provide. Please let me know if any further information would be useful.
I geuss you forgot to do you productcode +1 somewhere. Why aren't you using auto increment on you pk? That will work any time.
There is, as far as I can see, no value in your insert for the primary key (usually called id).
I guess you did not use some sort of auto incrementing on that field.
I am trying to insert data into a database using a three-tier architecture, but I am stuck and I cannot proceed further.
This is my code
First is UI part:
public void assignField()
{
string maritalCondition = "";
string sex = "";
assignObj.Registered_Date = dateTimePicker1_Date.Value;
assignObj.First_Name = txt_FirstName.Text;
if (comboBox2_MaritalStatus.SelectedIndex == 0)
{
maritalCondition = "Single";
}
else
maritalCondition = "Married";
assignObj.Marital_Status = maritalCondition;
if (RadioButton_Male.Checked == true)
sex = "Male";
else
sex = "Female";
assignObj.Gender = sex;
this.txt_Age.Text = Convert.ToInt32(age).ToString();
}
private void btnRegister_Click(object sender, EventArgs e)
{
assignField();
}
Next is the middle tier:
public class CustomerDataType
{
private DateTime registered_Date;
private string first_Name;
private int age;
private string marital_Status;
private string gender;
public DateTime Registered_Date
{
get { return registered_Date; }
set { registered_Date = value; }
}
public string First_Name
{
get { return first_Name; }
set { first_Name = value; }
}
public int Age
{
get { return age; }
set { age = value; }
}
public string Marital_Status
{
get { return marital_Status; }
set { marital_Status = value; }
}
public string Gender
{
get { return gender; }
set { gender = value; }
}
public void insertInfo()
{
CustomerDataAccess insertObj = new CustomerDataAccess(Registered_Date, First_Name, Age, Marital_Status, Gender);
insertObj.insertCustomerInfo();
}
}
and last is the data access tier:
public class CustomerDataAccess
{
public CustomerDataAccess(DateTime Registered_Date, string First_Name, int Age, string Marital_Status, string Gender)
{
this.registrationDate = Registered_Date;
this.fName = First_Name;
this.userAge = Age;
this.marriageStatus = Marital_Status;
this.userGender = Gender;
}
SqlConnection con;
SqlCommand cmd;
DateTime registrationDate;
string fName = "";
int userAge;
string marriageStatus;
string userGender;
public void insertCustomerInfo()
{
try
{
con = new SqlConnection("Data Source=LAKHE-PC;Initial Catalog=Sahakari;Integrated Security=True");
con.Open();
cmd = con.CreateCommand();
cmd.CommandText = "sp_registerCust";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#Registered_Date", SqlDbType.DateTime);
cmd.Parameters["#Registered_Date"].Value = registrationDate;
cmd.Parameters.Add("#First_Name", SqlDbType.VarChar);
cmd.Parameters["#First_Name"].Value = fName;
cmd.Parameters.Add("#Age", SqlDbType.Int.ToString());
cmd.Parameters["#Age"].Value = userAge;
cmd.Parameters.Add("#Marital_Status", SqlDbType.VarChar);
cmd.Parameters["#Marital_Status"].Value = marriageStatus;
cmd.Parameters.Add("#Gender", SqlDbType.VarChar);
cmd.Parameters["#Gender"].Value = userGender;
cmd.ExecuteNonQuery();
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Here with the stored procedure, there is no problem and and from SQL Server I can insert data into table easily. But from windows form, it does not insert data in table. Plz help me.
I'll do something like below
UI
CustomerHandler custHandler = new CustomerHandler();
// create Customer object and pass to insert method
if (custHandler.InsertCustomer(new Customer(){
FirstName = txt_FirstName.Text, Registered_Date =dateTimePicker1_Date.Value,
//decalare other parameters....
))
{
// insert Success, show message or update label with succcess message
}
In my BL
public class CustomerHandler
{
// in BL you may have to call several DAL methods to perform one Task
// here i have added validation and insert
// in case of validation fail method return false
public bool InsertCustomer(Customer customer)
{
if (CustomerDataAccess.Validate(customer))
{
CustomerDataAccess.insertCustomer(customer);
return true;
}
return false;
}
}
In MY DAL
// this is the class you going to use to transfer data across the layers
public class Customer
{
public DateTime Registered_Date { get; set; }
public string FirstName { get; set; }
//so on...
}
public class CustomerDataAccess
{
public static void insertCustomer(Customer customer)
{
using (var con = new SqlConnection("Data Source=LAKHE-PC;Initial Catalog=Sahakari;Integrated Security=True"))
using (var cmd = con.CreateCommand())
{
con.Open();
cmd.CommandText = "sp_registerCust";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Registered_Date", customer.Registered_Date);
cmd.Parameters.AddWithValue("#FirstName", customer.FirstName);
// so on...
cmd.ExecuteNonQuery();
}
}
internal static bool Validate(Customer customer)
{
// some validations before insert
}
}
Your middle tier consists of classes holding the values you require in properties. Instead of writing the data access manually, try using the Entity Framework (EF) which does that for you.
Here (at MSDN) you can find a quickstart example which shows you how you can use it.
Instead of mapping the fields manually and executing a query, the Entity Framework does that which means you just have to assign the values to the object's properties and call SaveChanges() - the SQL code is created and executed automatically by the EF.
For further reading, there is also a lot to find here (at Stackoverflow).
I am facing problem while i am inserting new record from GUI part to database table. I have created database table Patient with id, name, age etc....id is identity primary key. My problem is while i am inserting duplicate name in table the control should go to else part, and display the message like...This name is already exits, pls try with another name...
but in my coding not getting..... Here is all the code...pls somebody point me out whats wrong or how do this???
GUILayer:
protected void BtnSubmit_Click(object sender, EventArgs e)
{
if (!Page.IsValid)
return;
int intResult = 0;
string name = TxtName.Text.Trim();
int age = Convert.ToInt32(TxtAge.Text);
string gender;
if (RadioButtonMale.Checked)
{
gender = RadioButtonMale.Text;
}
else
{
gender = RadioButtonFemale.Text;
}
string city = DropDownListCity.SelectedItem.Value;
string typeofdisease = "";
foreach (ListItem li in CheckBoxListDisease.Items)
{
if (li.Selected)
{
typeofdisease += li.Value;
}
}
typeofdisease = typeofdisease.TrimEnd();
PatientBAL PB = new PatientBAL();
PatientProperty obj = new PatientProperty();
obj.Name = name;
obj.Age = age;
obj.Gender = gender;
obj.City = city;
obj.TypeOFDisease = typeofdisease;
try
{
intResult = PB.ADDPatient(obj);
if (intResult > 0)
{
lblMessage.Text = "New record inserted successfully.";
TxtName.Text = string.Empty;
TxtAge.Text = string.Empty;
RadioButtonMale.Enabled = false;
RadioButtonFemale.Enabled = false;
DropDownListCity.SelectedIndex = 0;
CheckBoxListDisease.SelectedIndex = 0;
}
else
{
lblMessage.Text = "Name [<b>" + TxtName.Text + "</b>] alredy exists, try another name";
}
}
catch (Exception ex)
{
lblMessage.Text = ex.Message.ToString();
}
finally
{
obj = null;
PB = null;
}
}
BAL layer:
public class PatientBAL
{
public int ADDPatient(PatientProperty obj)
{
PatientDAL pdl = new PatientDAL();
try
{
return pdl.InsertData(obj);
}
catch
{
throw;
}
finally
{
pdl=null;
}
}
}
DAL layer:
public class PatientDAL
{
public string ConString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
public int InsertData(PatientProperty obj)
{
SqlConnection con = new SqlConnection(ConString);
con.Open();
SqlCommand com = new SqlCommand("LoadData",con);
com.CommandType = CommandType.StoredProcedure;
try
{
com.Parameters.AddWithValue("#Name", obj.Name);
com.Parameters.AddWithValue("#Age",obj.Age);
com.Parameters.AddWithValue("#Gender",obj.Gender);
com.Parameters.AddWithValue("#City", obj.City);
com.Parameters.AddWithValue("#TypeOfDisease", obj.TypeOFDisease);
return com.ExecuteNonQuery();
}
catch
{
throw;
}
finally
{
com.Dispose();
con.Close();
}
}
}
Property Class:
public class PatientProperty
{
private string name;
private int age;
private string gender;
private string city;
private string typedisease;
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
public int Age
{
get
{
return age;
}
set
{
age = value;
}
}
public string Gender
{
get
{
return gender;
}
set
{
gender = value;
}
}
public string City
{
get
{
return city;
}
set
{
city = value;
}
}
public string TypeOFDisease
{
get
{
return typedisease;
}
set
{
typedisease = value;
}
}
}
This is my stored Procedure:
CREATE PROCEDURE LoadData
(
#Name varchar(50),
#Age int,
#Gender char(10),
#City char(10),
#TypeofDisease varchar(50)
)
as
insert into Patient(Name, Age, Gender, City, TypeOfDisease)values(#Name,#Age, #Gender, #City, #TypeofDisease)
GO
Are you sure your LoadData stored proc is doing an insert instead of an update?
looks like your throwing the error, so it jumps down to your catch block.
You'll need to handle the error coming back from PB.ADDPatient and not the value
Does the record duplicated in the database? I am afraid you did not add the unique constraint for Names in the database!
If this is the case, and you are using SQL Server, check this:
SQL Server 2005 How Create a Unique Constraint?