ListBox doesnt show any results - c#

I'm trying to add an array of strings that holds information about people to a ListBox but i cant get it to show anything and i really dont know why.
This is the first class that is called when the button to add contacts to the list is clicked.
public partial class MainForm : Form
{
private ContactManager m_contacts;
public MainForm()
{
InitializeComponent();
m_contacts = new ContactManager();
InitializeGUI();
}
private void InitializeGUI()
{
txtFirstName.Text = string.Empty;
txtLastName.Text = string.Empty;
txtStreet.Text = string.Empty;
txtCity.Text = string.Empty;
txtZipCode.Text = string.Empty;
cmbCountry.Items.AddRange(Enum.GetNames(typeof(Countries)));
cmbCountry.DropDownStyle = ComboBoxStyle.DropDownList;
cmbCountry.SelectedIndex = (int)Countries.Sverige;
UpdateGUI();
}
private bool ReadInput(out Contact contact)
{
// skapar ett lokalt objekt av Contact-klassen
contact = new Contact();
// Lägger in ReadAdress till ett objekt i klassen Adress.
Address adr = ReadAddress();
contact.AddressData = adr; // skickar adress till contact-objekt
//bool readNameOK = ReadName();
// ReadName är OK så skickas det till AddContact.
if (ReadName())
{
m_contacts.AddContact(contact);
}
return ReadName();
} // ReadInput
private bool ReadName()
{
Contact contact = new Contact();
contact.FirstName = txtFirstName.Text;
contact.LastName = txtLastName.Text;
bool firstname = false;
bool lastname = false;
if (!InputUtility.ValidateString(contact.FirstName))
{
MessageBox.Show("You must enter a first name with atleast one character (not a blank)", "Error!",
MessageBoxButtons.OK, MessageBoxIcon.Error);
txtFirstName.Focus();
txtFirstName.Text = " ";
txtFirstName.SelectAll();
firstname = false;
}
else if (!InputUtility.ValidateString(contact.LastName))
{
MessageBox.Show("You must enter a last name with atleast one character (not a blank)", "Error!",
MessageBoxButtons.OK, MessageBoxIcon.Error);
txtLastName.Focus();
txtLastName.Text = " ";
txtLastName.SelectAll();
lastname = false;
}
return firstname && lastname;
}
private Address ReadAddress()
{
Address address = new Address();
address.Street = txtStreet.Text;
address.City = txtCity.Text;
address.ZipCode = txtZipCode.Text;
address.Country = (Countries)cmbCountry.SelectedIndex;
return address;
}
private void button1_Click(object sender, EventArgs e)
{
Contact contact;
if (ReadInput(out contact))
{
UpdateGUI();
}
}
private void UpdateGUI()
{
lstContacts.Items.Clear();
lstContacts.Items.AddRange(m_contacts.GetContactsInfo());
lblCount.Text = m_contacts.Count().ToString();
}
private void lstContacts_SelectedIndexChanged(object sender, EventArgs e)
{
UpdateContactInfoFromRegistry();
}
private void UpdateContactInfoFromRegistry()
{
Contact contact = m_contacts.GetContact(lstContacts.SelectedIndex);
cmbCountry.SelectedIndex = (int)contact.AddressData.Country;
txtFirstName.Text = contact.FirstName;
txtLastName.Text = contact.LastName;
txtCity.Text = contact.AddressData.City;
txtStreet.Text = contact.AddressData.Street;
txtZipCode.Text = contact.AddressData.ZipCode;
}
}
This class then calls this class
public class ContactManager
{
private List<Contact> m_contactRegistry;
public ContactManager()
{
m_contactRegistry = new List<Contact>();
}
public int Count()
{
int count = m_contactRegistry.Count();
return count;
}
public bool CheckIndex(int index)
{
if (index >= 0 && index < m_contactRegistry.Count())
return true;
else return false;
}
public bool AddContact(string firstName, string lastName, Address addressIn)
{
Contact contactObj = new Contact();
bool result = false;
if (!result)
{
contactObj.FirstName = firstName;
contactObj.LastName = lastName;
contactObj.AddressData = addressIn;
m_contactRegistry.Add(contactObj);
result = true;
}
return result;
}
public bool AddContact(Contact contactIn)
{
if (contactIn == null)
{
return false;
}
else
{
m_contactRegistry.Add(contactIn);
return true;
}
}
public bool changeContact(Contact contactIn, int index)
{
if (CheckIndex(index))
{
Contact contact = (Contact)m_contactRegistry[index];
//contact.ToString = contactIn;
return true;
}
else return false;
}
public bool DeleteContact(int index)
{
if (CheckIndex(index))
{
m_contactRegistry.RemoveAt(index);
return true;
}
else return false;
}
public Contact GetContact(int index)
{
if (!CheckIndex(index))
return null;
else return m_contactRegistry[index];
}
public string[] GetContactsInfo()
{
string[] strInfoStrings = new string[m_contactRegistry.Count];
int i = 0;
foreach (Contact contactObj in m_contactRegistry)
{
strInfoStrings[i++] = contactObj.ToString();
}
return strInfoStrings;
}
}
Any help regarding why the arrays wont show up in the listbox would be much appriciated, thanks.

Your ReadName() always returns false, there for it never adds the contacts.
EDIT:
A clearer code
private Contact ReadInput()
{
Contact contact = new Contact();
contact.FirstName = txtFirstName.Text;
contact.LastName = txtLastName.Text;
contact.AddressData = new Address
{
Street = txtStreet.Text,
City = txtCity.Text,
ZipCode = txtZipCode.Text,
Country = (Countries) cmbCountry.SelectedIndex
};
return contact;
}
private bool ValidateContact(Contact contact)
{
if ( !InputUtility.ValidateString( contact.FirstName ) )
{
MessageBox.Show( "You must enter a first name with atleast one character (not a blank)", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error );
txtFirstName.Focus();
txtFirstName.Text = " ";
txtFirstName.SelectAll();
return false;
}
else if ( !InputUtility.ValidateString( contact.LastName ) )
{
MessageBox.Show( "You must enter a last name with atleast one character (not a blank)", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error );
txtLastName.Focus();
txtLastName.Text = " ";
txtLastName.SelectAll();
return false;
}
return true;
}
private void button1_Click( object sender, EventArgs e )
{
Contact contact = ReadInput();
if ( ValidateContact( contact ) )
{
m_contacts.AddContact(contact);
UpdateGUI();
}
}

Related

avoid local host ID to be edited by customers

i have an orderdetails page wherein customers can view their history page. And this is the url:
when i change the ID from 13 to lets say 14, it still shows the details on whats inside ID#14. What i want to happen is to have an error when customers try to change the localhost ID. Or to restrict the ID to be edited? Really dont have any idea on what to do. Encryption?
By the way here is the orderdetails code behind: (this is in user control)
public partial class ucCustomerOrder1 : System.Web.UI.UserControl
{
public bool CanIUpdateStatus;
public string TransactionNoText
{
get { return txtTransactionNo.Text; }
set { txtTransactionNo.Text = value; }
}
public bool IsAuthorizedToAddStatus
{
set { CanIUpdateStatus = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Session["IslandGasAdmin/ST"] == null)
{
txtTransactionNo.ReadOnly = true;
btnGo.Visible = false;
}
else
{
txtTransactionNo.ReadOnly = false;
btnGo.Visible = true;
}
if (txtTransactionNo.Text != string.Empty)
{
ShowOrderDetails(rblOrderDetails.SelectedValue, Convert.ToInt32(txtTransactionNo.Text));
}
else
{
rblOrderDetails.Visible = false;
Panel1.Visible = false;
Panel2.Visible = false;
Panel3.Visible = false;
Panel4.Visible = false;
}
}
}
private void ShowOrderDetails(string PanelId, int OrderNo)
{
Panel1.Visible = false;
Panel2.Visible = false;
Panel3.Visible = false;
Panel4.Visible = false;
rblOrderDetails.Visible = false;
if (IsOrderNoValid(OrderNo))
{
rblOrderDetails.Visible = true;
if (PanelId == "1")
{
ShoppingCart k = new ShoppingCart
{
Flag = OrderNo
};
DataTable dtCustomerDetails = k.GetOrderList();
if (dtCustomerDetails.Rows.Count > 0)
{
Panel1.Visible = true;
lblCustomerName.Text = Convert.ToString(dtCustomerDetails.Rows[0]["CustomerName"]);
lblCustomerPhoneNo.Text = Convert.ToString(dtCustomerDetails.Rows[0]["CustomerPhoneNo"]);
lblCustomerEmailID.Text = Convert.ToString(dtCustomerDetails.Rows[0]["CustomerEmailID"]);
lblTotalPrice.Text = String.Format("{0:#,000.00}",dtCustomerDetails.Rows[0]["TotalPrice"]);
lblTotalProducts.Text = Convert.ToString(dtCustomerDetails.Rows[0]["TotalProducts"]);
txtCustomerAddress.Text = Convert.ToString(dtCustomerDetails.Rows[0]["CustomerAddress"]);
lblPaymentMethod.Text = Convert.ToString(dtCustomerDetails.Rows[0]["PaymentMethod"]);
}
}
if (PanelId == "2")
{
Panel2.Visible = true;
ShoppingCart k = new ShoppingCart()
{
Flag = OrderNo
};
dlProducts.DataSource = k.GetTransactionDetails(); ;
dlProducts.DataBind();
}
if (PanelId == "3")
{
Panel3.Visible = true;
DropDownStatus.Visible = CanIUpdateStatus;
txtStatus.Visible = false;
//txtStatus.Visible = CanIUpdateStatus;
btnAdd.Visible = CanIUpdateStatus;
GetSetOrderStatus(0);
}
}
else
{
Panel4.Visible = true;
}
}
private bool IsOrderNoValid(int OrderNo)
{
ShoppingCart k = new ShoppingCart
{
Flag = OrderNo
};
DataTable dtCustomerDetails = k.GetOrderList();
if (dtCustomerDetails.Rows.Count > 0)
return true;
else
return false;
}
private void GetSetOrderStatus(int Flag)
{
ShoppingCart k = new ShoppingCart
{
OrderStatus = DropDownStatus.SelectedValue,
OrderNo = txtTransactionNo.Text,
Flag = Flag
};
DataTable dt = k.GetSetOrderStatus();
gvOrderStatus.DataSource = dt;
gvOrderStatus.DataBind();
//txtStatus.Text = string.Empty;
//DropDownStatus.SelectedValue = string.Empty;
}
please do help me, thank you

C# adding a row to a datagridview in another form

I'm having difficulty trying to pass information from one form in which a user inputs a lot of employee data and presses a Submit button and the information is to display as an added row to a datagridview table. What can I do to fix this issue?
The code I have at present:
Form1:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void getEmployeedata(Manager manager)
{
int age;
int years;
int salary;
manager.FirstName = firstnameBox.Text;
manager.LastName = lastnameBox.Text;
manager.Gender = genderBox.Text;
manager.Title = titleBox.Text;
manager.Exempt = exemptBox.Text;
if (int.TryParse(ageBox.Text, out age))
{
manager.Age = age;
if (int.TryParse(yearsBox.Text, out years))
{
manager.Years = years;
if (int.TryParse(salaryBox.Text, out salary))
{
manager.Salary = salary;
}
else
{
MessageBox.Show("Wrong salary input");
}
}
else
{
MessageBox.Show("Wrong Years input");
}
}
else
{
MessageBox.Show("Wrong age input");
}
}
private void submitButton_Click(object sender, EventArgs e)
{
Manager manager = new Manager();
getEmployeedata(manager);
EmployeeListing form2 = new EmployeeListing(manager.FirstName, manager.LastName, manager.Gender, manager.Age, manager.Years, manager.Title, manager.Exempt, manager.Salary);
form2.Show();
}
private void clearButton_Click(object sender, EventArgs e)
{
firstnameBox.Text = "";
lastnameBox.Text = "";
genderBox.Text = "";
ageBox.Text = "";
yearsBox.Text = "";
titleBox.Text = "";
exemptBox.Text = "";
salaryBox.Text = "";
}
}
class Employee
{
private string firstName = "";
private string lastName = "";
private string gender = "";
private int age = 0;
private int years = 0;
public string FirstName
{
get { return firstName; }
set { firstName = value; }
}
public string LastName
{
get { return lastName; }
set { lastName = value; }
}
public string Gender
{
get { return gender; }
set { gender = value; }
}
public int Age
{
get { return age; }
set { age = value; }
}
public int Years
{
get { return years; }
set { years = value; }
}
} //end Employee class
class Manager : Employee
{
private string title = "";
private string exempt = "";
private int salary = 0;
public string Title
{
get { return title; }
set { title = value; }
}
public string Exempt
{
get { return exempt; }
set { exempt = value; }
}
public int Salary
{
get { return salary; }
set { salary = value; }
}
} //end Manager class
Form2:
public partial class EmployeeListing : Form
{
public EmployeeListing(string firstname, string lastname, string gender, int age, int years, string title, string exempt, int salary)
{
InitializeComponent();
employeeList.Rows.Add(firstname, lastname, gender, age, years, title, exempt, salary);
}
}
In your click handler, you are initializing a EmployeeListing form every time you click the button, and you probably only want to do this once.So, keep the instance of your EmployeeListing outside of the click handler and only create one instance of it so that you can access it on subsequent clicks. To keep adding data to the form, you could create a public method on the EmployeeListing form that adds the row data and then call this method from your click handler, using the instance of the form.
This is untested, but just to get you started...
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void getEmployeedata(Manager manager)
{
int age;
int years;
int salary;
EmployeeListing form2;
manager.FirstName = firstnameBox.Text;
manager.LastName = lastnameBox.Text;
manager.Gender = genderBox.Text;
manager.Title = titleBox.Text;
manager.Exempt = exemptBox.Text;
if (int.TryParse(ageBox.Text, out age))
{
manager.Age = age;
if (int.TryParse(yearsBox.Text, out years))
{
manager.Years = years;
if (int.TryParse(salaryBox.Text, out salary))
{
manager.Salary = salary;
}
else
{
MessageBox.Show("Wrong salary input");
}
}
else
{
MessageBox.Show("Wrong Years input");
}
}
else
{
MessageBox.Show("Wrong age input");
}
}
private void submitButton_Click(object sender, EventArgs e)
{
Manager manager = new Manager();
getEmployeedata(manager);
if (form2 == null)
{
EmployeeListing form2 = new EmployeeListing();
form2.Show();
}
form2.AddRowData(manager.FirstName, manager.LastName, manager.Gender, manager.Age, manager.Years, manager.Title, manager.Exempt, manager.Salary);
}
private void clearButton_Click(object sender, EventArgs e)
{
firstnameBox.Text = "";
lastnameBox.Text = "";
genderBox.Text = "";
ageBox.Text = "";
yearsBox.Text = "";
titleBox.Text = "";
exemptBox.Text = "";
salaryBox.Text = "";
}
}
class Employee
{
private string firstName = "";
private string lastName = "";
private string gender = "";
private int age = 0;
private int years = 0;
public string FirstName
{
get { return firstName; }
set { firstName = value; }
}
public string LastName
{
get { return lastName; }
set { lastName = value; }
}
public string Gender
{
get { return gender; }
set { gender = value; }
}
public int Age
{
get { return age; }
set { age = value; }
}
public int Years
{
get { return years; }
set { years = value; }
}
} //end Employee class
class Manager : Employee
{
private string title = "";
private string exempt = "";
private int salary = 0;
public string Title
{
get { return title; }
set { title = value; }
}
public string Exempt
{
get { return exempt; }
set { exempt = value; }
}
public int Salary
{
get { return salary; }
set { salary = value; }
}
} //end Manager class
public partial class EmployeeListing : Form
{
public EmployeeListing()
{
InitializeComponent();
}
public AddRowData(string firstname, string lastname, string gender, int age, int years, string title, string exempt, int salary)
{
employeeList.Rows.Add(firstname, lastname, gender, age, years, title, exempt, salary);
}
}
You can create a DataTable on the EmployeeListing() constructor and set the DataSource:
public EmployeeListing(string firstname, string lastname, string gender, int age, int years, string title, string exempt, int salary)
{
InitializeComponent();
//employeeList.Rows.Add(firstname, lastname, gender, age, years, title, exempt, salary);
DataTable dtSource = new DataTable();
dtSource.Columns.Add("firstname", typeof(string));
dtSource.Columns.Add("lastname", typeof(string));
dtSource.Columns.Add("gender", typeof(string));
dtSource.Columns.Add("age", typeof(string));
dtSource.Columns.Add("years", typeof(string));
dtSource.Columns.Add("title", typeof(string));
dtSource.Columns.Add("exempt", typeof(string));
dtSource.Columns.Add("salary", typeof(string));
DataRow dtRow;
dtRow = dtSource.NewRow();
dtRow[0] = firstname;
dtRow[1] = lastname;
dtRow[2] = gender;
dtRow[3] = age;
dtRow[4] = years;
dtRow[5] = Title;
dtRow[6] = exempt;
dtRow[7] = salary;
dtSource.Rows.Add(dtRow.ItemArray);
employeeList.DataSource = dtSource;
}
You should also out this in another function and not in the constructor if you will add rows to the gridview more than once.

My message wont show on my textbox?

I am trying to fill a form (Movie information such as Title, Year and Genre) and then show it in a textbox (enable=false).
I have 2 classes and a Form (with 2 textboxes (for user input), 2 buttons, 1 to register the movie infos, and 1 to show the infos in a 3rd textbox (the one that is Disabled).
class Movies
{
public string Title { get; set; }
public int Year { get; set; }
public string ReturnMovie()
{
return Title + " (" + Year.ToString() + ")";
}
}
class Genres
{
public string Genre { get; set; }
public string ReturnGenre()
{
return Genre;
}
}
MainForm:
bool btnRegisterClicked = false;
Movies m1 = new Movies();
Genres g1 = new Genres();
private void btnRegister_Click(object sender, EventArgs e)
{
btnRegisterClicked = true;
if (btnRegisterClicked == true)
{
if (txtTitle.Text.Length == 0)
{
MessageBox.Show("Enter a title for the movie.");
btnRegisterClicked = false;
}
else if (txtYear.Text.Length < 4)
{
MessageBox.Show("Enter a valid year.");
btnRegisterClicked = false;
}
else if (chkGenre.SelectedIndex == -1)
{
MessageBox.Show("Select the genre(s) of the movie.");
btnRegisterClicked = false;
}
else
{
txtTitle.Text = m1.Title;
txtYear.Text = m1.Year.ToString();
chkGenre.Text = g1.Genre;
}
txtTitle.Clear();
txtYear.Clear();
chkGenre.ClearSelected();
}
}
private void btnShow_Click(object sender, EventArgs e)
{
txtShow.Text = m1.ReturnMovie() + g1.ReturnGenre();
}
}
What am I doing wrong ?
The assignments in your else block are backwards. You're setting the TextBox to the un-initalized contents of m1 and g1, and then immediately .Clear()ing them out.
else
{
m1.Title = txtTitle.Text;
m1.Year = int.Parse(txtYear.Text);
g1.Genre = chkGenre.Text
}
You need to assign values to variables not to controls..., change following
else
{
txtTitle.Text = m1.Title;
txtYear.Text = m1.Year.ToString();
chkGenre.Text = g1.Genre;
}
to
else
{
m1.Title = txtTitle.Text;
m1.Year = int.Parse(txtYear.Text);
g1.Genre = chkGenre.Text;
}

How to only run methods when called?

I have a bunch of code below. However, I am hitting some bugs because the methods Move() and Genius() are running logic too much. I only want to two methods to run if they are being called by the submit click method. How can I do this?
namespace ShotgunApp
{
public partial class SingleGame : PhoneApplicationPage
{
public static class AmmoCount
{
public static int userAmmo = startVars.startAmmo;
public static int geniusAmmo = startVars.startAmmo;
}
public static class Global
{
public static int lives = 1;
public static string GeniusMove;
public static string UserMove;
}
public SingleGame()
{
InitializeComponent();
GeniusAmmo.Text = "ammo: " + AmmoCount.geniusAmmo;
UserAmmo.Text = "ammo: " + AmmoCount.userAmmo;
}
private void submit_Click(object sender, RoutedEventArgs e)
{
if (((String)submit.Content) == "Submit")
{
Move();
submit.Content = "Wait for Genius...";
uReload.IsEnabled = false;
uFire.IsEnabled = false;
uShield.IsEnabled = false;
Genius();
}
else if (((String)submit.Content) == "Go!")
{
GeniusSpeak.Text = "";
OutcomeDesc.Text = "You have " + Move() + " and Genius has " + Genius();
Outcome.Text = "ANOTHER ROUND...";
submit.Content = "Continue";
}
else if (((String)submit.Content) == "Continue")
{
uReload.IsEnabled = true;
uFire.IsEnabled = true;
uShield.IsEnabled = true;
OutcomeDesc.Text = "";
Outcome.Text = "";
submit.Content = "Submit";
}
}
public string Move()
{
if (uReload.IsChecked.HasValue && uReload.IsChecked.Value == true)
{
UserAmmo.Text = "ammo: " + ++AmmoCount.userAmmo;
Global.UserMove = "reloaded";
}
else if (uShield.IsChecked.HasValue && uShield.IsChecked.Value == true)
{
Global.UserMove = "shielded";
}
else if (uFire.IsChecked.HasValue && uFire.IsChecked.Value == true)
{
UserAmmo.Text = "ammo: " + --AmmoCount.userAmmo;
Global.UserMove = "fired";
}
else
{
submit.Content = "Enter a move!";
}
return Global.UserMove;
}
public string Genius()
{
GeniusSpeak.Text = "Genius has moved";
submit.Content = "Go!";
Random RandomNumber = new Random();
int x = RandomNumber.Next(0, 3);
if (x == 0)
{
Global.GeniusMove = "reloaded";
GeniusAmmo.Text = "ammo: " + ++AmmoCount.geniusAmmo;
}
else if (x == 1)
{
Global.GeniusMove = "shielded";
}
else if (x == 2)
{
Global.GeniusMove = "fired";
GeniusAmmo.Text = "ammo: " + ++AmmoCount.geniusAmmo;
}
return Global.GeniusMove;
}
}
}
Store the last results in data members:
private string lastMoveResult = string.Empty;
private string lastGeniusResult = string.Empty;
private void submit_Click(object sender, RoutedEventArgs e)
{
if (((String)submit.Content) == "Submit")
{
lastMoveResult = Move();
submit.Content = "Wait for Genius...";
uReload.IsEnabled = false;
uFire.IsEnabled = false;
uShield.IsEnabled = false;
lastGeniusResult = Genius();
}
else if (((String)submit.Content) == "Go!")
{
GeniusSpeak.Text = "";
OutcomeDesc.Text = "You have " + lastMoveResult + " and Genius has " + lastGeniusResult ;
Outcome.Text = "ANOTHER ROUND...";
submit.Content = "Continue";
}

Problem while inserting data from GUI layer to database

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?

Categories