I am trying to bind the content of a label based on the result I get from running a stored procedure. Here is my XAML:
<StackPanel Orientation="Horizontal" HorizontalAlignment="Left">
<Label Content="Date:" FontSize="10" />
<Label x:Name="HomeScreenLabelInfoDate" FontSize="10" FontWeight="DemiBold" FontStyle="Italic" Content="{Binding InfoDate}"/>
<Label Content="-"/>
<Label Content="Author:" FontSize="10"/>
<Label x:Name="HomeScreenLabelInfoAuthor" Margin="3 0" FontSize="10" FontWeight="DemiBold" FontStyle="Italic" Content="{Binding InfoAuthor}"/>
</StackPanel>
And here is my code-behind:
public HomeUserControl()
{
InitializeComponent();
try
{
GetPublications();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
public class NewsData
{
public string InfoTitle { get; set; }
public string InfoMessage { get; set; }
public string InfoDate { get; set; }
public string InfoAuthor { get; set; }
}
public void GetPublications()
{
string connstr = ConfigurationManager.ConnectionStrings["connstr"].ConnectionString;
using (var Connect = new SqlConnection(connstr))
{
Connect.Open();
using (var Command = new SqlCommand("[dbo].[spNewsManagementTb_DisplayNews]", Connect))
{
Command.CommandType = CommandType.StoredProcedure;
Command.Parameters.Add("#entity_id", SqlDbType.VarChar).Value = LoggedInData.LoggedInstitutionId;
SqlDataReader dr = Command.ExecuteReader();
while (dr.Read())
{
string newsTitle = dr.GetString(0);
string newsMessage = dr.GetString(1);
string newsAuthor = dr.GetString(2);
DateTime newsDate = dr.GetDateTime(3);
string newsDateFormated = newsDate.ToString("dddd, dd MMMM yyyy");
NewsData newsData = new NewsData();
newsData.InfoTitle = newsTitle;
newsData.InfoDate = newsDateFormated;
newsData.InfoAuthor = newsAuthor;
}
dr.Close();
Connect.Close();
}
}
}
Whenever I run the application, I don't see any data on my GUI. I have been able to overcome this by directly assigning the values of the labels from the values read from query but I would like to keep on using data binding throughout the code for consistency but this one is proving quite difficult to implement.
EDIT
I would like to mention that I am a beginner in programming so I am not really good at understanding all the concepts but the INotifyPropertyChanged property has thrown multiple errors. Here is the code after including the Notify property:
public HomeUserControl()
{
InitializeComponent();
try
{
var newsData = GetPublications();
this.DataContext = newsData;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
public NewsData : INotifyPropertyChanged
{
private string Title;
private string Message;
private string Date;
private string Author;
public event PropertyChangedEventHandler PropertyChanged;
public NewsData(string infoTitle, string infoMessage, string infoDate, string infoAuthor)
{
this.Author = infoAuthor;
this.Date = infoDate;
this.Message = infoMessage;
this.Title = infoTitle;
}
public string InfotAuthor
{
get { return Author; }
set
{
Author = InfotAuthor;
OnPropertyChanged();
}
}
public string InfotDate
{
get { return Date; }
set
{
Date = InfotDate;
OnPropertyChanged();
}
}
public string InfotMessage
{
get { return Message; }
set
{
Author = InfotMessage;
OnPropertyChanged();
}
}
public string InfotTitle
{
get { return Title; }
set
{
Author = InfotTitle;
OnPropertyChanged();
}
}
protected void OnPropertyChanged(string Author = null, string Message = null, string Date = null, string Title = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(Author));
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(Message));
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(Date));
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(Title));
}
}
public NewsData GetPublications()
{
string connstr = ConfigurationManager.ConnectionStrings["connstr"].ConnectionString;
using (var Connect = new SqlConnection(connstr))
{
Connect.Open();
using (var Command = new SqlCommand("[dbo].[spNewsManagementTb_DisplayNews]", Connect))
{
Command.CommandType = CommandType.StoredProcedure;
Command.Parameters.Add("#entity_id", SqlDbType.VarChar).Value = LoggedInData.LoggedInstitutionId;
SqlDataReader dr = Command.ExecuteReader();
while (dr.Read())
{
string newsTitle = dr.GetString(0);
string newsMessage = dr.GetString(1);
string newsAuthor = dr.GetString(2);
DateTime newsDate = dr.GetDateTime(3);
string newsDateFormated = newsDate.ToString("dddd, dd MMMM yyyy");
NewsData newsData = new NewsData();
newsData.InfoTitle = newsTitle;
newsData.InfoDate = newsDateFormated;
newsData.InfoAuthor = newsAuthor;
}
dr.Close();
Connect.Close();
}
}
return newsData;
}
The errors are arising from the GetPublications() method, which does not recognise NewsData
Make following changes to your code.
Make GetPublications() to return "NewsData" type like below,
public NewsData GetPublications()
{
string connstr = ConfigurationManager.ConnectionStrings["connstr"].ConnectionString;
NewsData newsData = new NewsData();
using (var Connect = new SqlConnection(connstr))
{
Connect.Open();
using (var Command = new SqlCommand("[dbo].[spNewsManagementTb_DisplayNews]", Connect))
{
Command.CommandType = CommandType.StoredProcedure;
Command.Parameters.Add("#entity_id", SqlDbType.VarChar).Value = LoggedInData.LoggedInstitutionId;
SqlDataReader dr = Command.ExecuteReader();
while (dr.Read())
{
string newsTitle = dr.GetString(0);
string newsMessage = dr.GetString(1);
string newsAuthor = dr.GetString(2);
DateTime newsDate = dr.GetDateTime(3);
string newsDateFormated = newsDate.ToString("dddd, dd MMMM yyyy");
newsData.InfoTitle = newsTitle;
newsData.InfoDate = newsDateFormated;
newsData.InfoAuthor = newsAuthor;
}
dr.Close();
Connect.Close();
}
}
return newsData;
}
In code-behind (constructor) of your user-control do the following changes,
public HomeUserControl()
{
InitializeComponent();
try
{
var newsData = GetPublications();
this.DataContext = newsData;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Implement INotifyPropertyChanged for NewsData class. See below link on how to achieve this
https://learn.microsoft.com/en-us/dotnet/framework/wpf/data/how-to-implement-property-change-notification
Small suggestion :- I prefer to make my database call in async way so that my user-control loads and waits for the data to come and bind.
Give a try and let us know if you still have further any issues.
Edit:- - Added extra piece of code after updated question.
Hi,
I have seen some mistakes from your code.
In your .xaml you are using "InfoDate" and "InfoAuthor" to bind to your label's.
But your NewsData does not have those properties.
Your NewsData properties names are "InfotAuthor" and "InfotDate" - It has "t" in it
I have used your xaml code (after making above changes).
Without INotifyPropertyChanged inheritance, I am able to see the data. I guess if you make above changes then you should be able to see the data in your view.
If you want to implement INotifyPropertyChanged, you can follow as below,
public class NewsData : INotifyPropertyChanged
{
private string _title;
private string _message;
private string _date;
private string _author;
public string InfoAuthor
{
get { return _author; }
set
{
_author = value;
OnPropertyChanged("InfoAuthor");
}
}
public string InfoDate
{
get { return _date; }
set
{
_date = value;
OnPropertyChanged("InfoDate");
}
}
public string InfoMessage
{
get { return _message; }
set
{
_message = value;
OnPropertyChanged("InfoMessage");
}
}
public string InfoTitle
{
get { return _title; }
set
{
_title = value;
OnPropertyChanged("InfoTitle");
}
}
protected void OnPropertyChanged(string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
}
I have made private members to start with "_" with camel casing (this is just correct naming conventions for back-end fields)
I have implemented OnPropertyChanged() method and I am calling from each property setter method.
In your setter method, you are trying to set like below which is wrong,
Date = InfotDate;
You need to set as "Date = value;"
Hope you can understand the difference from my updated answer.
Give a try and let us know in case if you still have any other issue.
If it answers your question then kindly accept it as answer.
Related
I am new to MVC.I am using a class library as Model and it reads data from the database and stores it in a Collection. Here is the code from the class library which reads records from sql database:
public IList<SemesterDetails> Read(User user )
{
string code; string name; int credits;int selfStudy;int modHrsPerWeek;
List<SemesterDetails> q = new List<SemesterDetails>();
using (SqlConnection db = new SqlConnection(AppConnect.Connection))
{
string query = "SELECT moduleCode,moduleName,modCredits,modHrsPerWeek,modHrsLeft FROM [Module] WHERE userName=#userName";
try
{
using (SqlCommand command=new SqlCommand(query,db))
{
if (db.State == ConnectionState.Closed)
{
db.Open();
command.Parameters.AddWithValue("#userName",user.UserName);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
code = reader.GetString(0);
name = reader.GetString(1);
credits = reader.GetInt32(2);
modHrsPerWeek = reader.GetInt32(3);
selfStudy = reader.GetInt32(4);
SemesterDetails semester = new SemesterDetails(code, name, credits,selfStudy);
q.Add(semester);
}
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
return q;
}
This gets called this action of the controller shown below:
public ActionResult EditStudyHrs(User user)
{
List <SemesterDetails >list= dataHandle.Read(user).ToList();
List<string> str = new List<string>();
foreach (var item in list)
{
str.Add(item.ModuleCode);
}
ViewBag.Modules = new SelectList(str, "ModuleCode", "ModuleCode");
return View();
}
I would like to bind Module code property to a Dropdownlist in this view:
<div class="form-horizontal">
<h4>Details</h4>
<hr />
#Html.DropDownList("Modules","SelctModuleCode")
</div>
SemesterDetails class:
public class SemesterDetails : ModuleInfo
{
private int numOfSemWeeks;
public int NumOfSemWeeks
{
get { return numOfSemWeeks; }
set { numOfSemWeeks = value; }
}
private DateTime startdate;
public DateTime StartDate
{
get { return startdate; }
set { startdate = value; }
}
private int studyHrsPerweek;
public int StudyHrsPerweek
{
get { return studyHrsPerweek; }
set { studyHrsPerweek = value; }
}
private DateTime endDate;
public DateTime EndDate
{
get { return endDate; }
set { endDate = value; }
}
private int selfStudy;
public int SelfStudy
{
get { return selfStudy; }
set { selfStudy = value; }
}
public SemesterDetails(string code,string name,int credits,int selfStudy)
{
this.ModuleCode = code;
this.ModuleName = name;
this.ModuleCredits = credits;
this.SelfStudy = selfStudy;
}
Try this
action
using Microsoft.AspNetCore.Mvc.Rendering;
.....
public ActionResult EditStudyHrs(User user)
{
var list= dataHandle.Read(user).ToList();
ViewBag.Modules = list.Select(i=> new SelectListItem { Value=i.ModuleCode, Text = i.ModuleName}).ToList();
var model= new SemesterDetails ();
return View(model);
}
view
#model SemesterDetails
.....
#Html.DropDownListFor(m => m.ModuleCode,#ViewBag.Modules, "Select Module")
or new syntax
<select class="form-control" asp-for="#Model.ModuleCode" asp-items="#ViewBag.Modules"></select>
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 have problems with updating WinGridView after i am pressing my Update Button. I am using BindingList with use of INotifyPropertyChanged property. And still can't get to make my gridview to update.
Below is code from my short test program:
public Form1()
{
InitializeComponent();
//create BindingList
using(SqlConnection connection = new SqlConnection(SQLconnectionString))
{
connection.Open();
using(SqlCommand command = new SqlCommand(SelectCustomer, connection))
{
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
customerList.Add(new Customers(reader["CntId"].ToString(), reader["Name"].ToString(), reader["Surname"].ToString()));
}
}
}
}
customersBindingSource = new BindingSource(customerList, null);
ugv_contacts.DataSource = customersBindingSource;
}
//update button
private void btn_UpdateCustomer_Click(object sender, EventArgs e)
{
using (SqlConnection conDataBase = new SqlConnection(SQLconnectionString))
{
try
{
conDataBase.Open();
SqlCommand updateCommand = conDataBase.CreateCommand();
updateCommand.CommandText = UpdateCustomerDet;
updateCommand.Parameters.AddWithValue("#CntId", Customer_Id);
updateCommand.Parameters.AddWithValue("#CntSurname", txt_surname.Text);
updateCommand.Parameters.AddWithValue("#CntName", txt_name.Text);
SqlDataReader myReader;
myReader = updateCommand.ExecuteReader();
customersBindingSource.ResetBindings(false);
}
catch (Exception ex) //v primeru napake se izvede to
{
MessageBox.Show(ex.Message);
}
}
}
public class Customers : INotifyPropertyChanged
{
public Customers(string id, string surname, string name)
{
CntId = id;
Name = name;
Surname = surname;
}
private string id;
private string surname;
private string name;
public string CntId { get { return id; } set { id = value; NotifyPropertyChanged("CntId"); } }
public string Surname { get { return surname; } set { surname = value; NotifyPropertyChanged("Surname"); } }
public string Name { get { return name; } set { name = value; NotifyPropertyChanged("Name"); } }
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string p)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(p));
}
}
Could someone please go throught it and told me what am i doing it wrong? I've searched and tested a lot of stackoverflow questions and still couldn't make my code to work correctly.
After some years i am still not quite at the end with the solution.
Could someone please tell me what am i doing wrong? Main problem is that .ResetBindings is not working. And i have no idea why.
Thank you in advance. Below it's my code:
public BindingSource contactSource = new BindingSource();
public BindingList<Contact> contactList = new BindingList<Contact>();
public Form1()
{
InitializeComponent();
contactList = GetBindingList_Contacts();
contactSource = new BindingSource(contactList, null);
ultraGrid1.DataSource = contactSource;
}
public BindingList<Contact> GetBindingList_Contacts()
{
using (SqlConnection connection = new SqlConnection(SQLconnectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(SelectCustomer, connection))
{
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
contactList.Add(new Contact
(
Convert.ToInt32(reader["CntId"]), reader["Name"].ToString(), reader["Surname"].ToString(), Convert.ToInt32(reader["CntAge"])
)
);
}
}
}
}
return new BindingList<Contact>(contactList);
}
private void btn_Edit_Click(object sender, EventArgs e)
{
int row = Convert.ToInt32(ultraGrid1.ActiveRow.ListIndex);
contactList[row].FirstName = txt_name.Text;
contactList[row].LastName = txt_surname.Text;
contactList[row].Age = Convert.ToInt32(txt_Age.Text);
//function that updated DB
}
private void btn_refresh_Click(object sender, EventArgs e)
{
contactSource.ResetBindings(true);
}
public static Contact GetBL_Contacts(int CntId)
{
Contact CtnDetail = new Contact();
using (SqlConnection conDataBase = new SqlConnection(SQLconnectionString))
{
try
{
conDataBase.Open();
SqlCommand selectCommand = conDataBase.CreateCommand();
selectCommand.CommandText = GetCustomerDetail;
selectCommand.Parameters.AddWithValue("#CntId", CntId);
SqlDataReader myReader;
myReader = selectCommand.ExecuteReader();
while (myReader.Read())
{
//produkt data
int sCntId = Convert.ToInt32(myReader["CntId"].ToString());
string sCntSurname = myReader["Surname"].ToString();
string sCntName = myReader["Name"].ToString();
int sCntAge = Convert.ToInt32(myReader["CntAge"]);
CtnDetail = new Contact
{
Id = sCntId,
FirstName = sCntName,
LastName = sCntSurname,
Age = sCntAge
};
}
}
catch (Exception ex) //v primeru napake se izvede to
{
MessageBox.Show(ex.Message);
}
}
return CtnDetail;
}
}
Class Contact
public class Contact : INotifyPropertyChanged
{
private int id;
private string firstName;
private string lastName;
private int age;
public Contact(int id, string firstName, string lastName, int age)
{
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
public Contact()
{
}
protected virtual void OnPropretyChanged(string propertyName)
{
var handler = this.PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
public int Id { get { return this.id; } set { if (this.id != value) { this.id = value; this.OnPropretyChanged("Id"); } } }
public string FirstName { get { return this.firstName; } set { if (this.firstName != value) { this.firstName = value; this.OnPropretyChanged("FirstName"); } } }
public string LastName { get { return this.lastName; } set { if (this.lastName != value) { this.lastName = value; this.OnPropretyChanged("LastName"); } } }
public int Age { get { return this.age; } set { if (this.age != value) { this.age = value; this.OnPropretyChanged("Age"); } } }
public event PropertyChangedEventHandler PropertyChanged;
I want to update some information when a save button is clicked.
I got an error
On : command.Parameters.Add("#doctorID", SqlDbType.Int).Value =
resident.Doctor.DoctorID; Saying: Object reference not set to an
instance of an object.
Im guessing I need to create some kind of object?
Button code:
private void btnSave_Click(object sender, RoutedEventArgs e)
{
Resident hello = new Resident();
hello.Doctor = new Doctor();
Resident residentID;
txtAdditionalInformation.Text = hello.addtionalInformation;
txtForename.Text = hello.FirstName;
txtSurname.Text = hello.Surname;
txtTitle.Text = hello.Title;
ResidentData.Update(hello);
}
update code (ResidentData Class):
public static void Update(Resident resident, SqlConnection connection, SqlTransaction transaction)
{
StringBuilder sqlString = new StringBuilder();
SqlCommand command;
sqlString.Append("UPDATE [Resident] SET ");
sqlString.Append("title = #title, ");
sqlString.Append("firstName = #firstName, ");
sqlString.Append("surname = #surname, ");
sqlString.Append("dateOfBirth = #dateOfBirth, ");
sqlString.Append("photo = #photo, ");
sqlString.Append("doctorID = #doctorID, ");
sqlString.Append("roomID = #roomID, ");
sqlString.Append("allergies = #allergies, ");
sqlString.Append("additionalInformation = #additionalInformation ");
sqlString.Append("WHERE residentID = #residentID ");
command = new SqlCommand(sqlString.ToString(), connection);
if ((transaction != null)) command.Transaction = transaction;
command.Parameters.Add("#residentID", SqlDbType.Int).Value = resident.ResidentID;
command.Parameters.Add("#title", SqlDbType.VarChar, 50).Value = Helper.GetValue(resident.Title);
command.Parameters.Add("#firstName", SqlDbType.VarChar, 100).Value = Helper.GetValue(resident.FirstName);
command.Parameters.Add("#surname", SqlDbType.VarChar, 100).Value = Helper.GetValue(resident.Surname);
command.Parameters.Add("#dateOfBirth", SqlDbType.DateTime).Value = Helper.GetValue(resident.DateOfBirth);
command.Parameters.Add("#photo", SqlDbType.Image, 2147483647).Value = Helper.GetValue(resident.Photo);
command.Parameters.Add("#doctorID", SqlDbType.Int).Value = resident.Doctor.DoctorID;
command.Parameters.Add("#roomID", SqlDbType.Int).Value = resident.Room.RoomID;
command.Parameters.Add("#allergies", SqlDbType.NText).Value = resident.Allergies;
command.Parameters.Add("#additionalInformation", SqlDbType.NText).Value = resident.addtionalInformation;
int rowsAffected = command.ExecuteNonQuery();
if (!(rowsAffected == 1))
{
throw new Exception("An error has occurred while updating Resident details.");
}
}
*Residence Class:
{
public class Resident
{
private int residentID;
private string title;
private string firstName;
private string surname;
private string searchText;
private System.DateTime dateOfBirth;
private byte[] photo;
private Room room;
private Doctor doctor;
private string nhs;
private string residentBarcode;
private string allergies;
private string additionalInformation;
public Resident()
: base()
{
}
public Resident(int newResidentID, string newTitle, string newFirstName, string newSurname, string newSearchText, System.DateTime newDateOfBirth, byte[] newPhoto, Room newRoom, Doctor newDoctor, string newNhs, string newResidentBarcode, string newAllergies, string newAdditionalInformation)
: base()
{
residentID = newResidentID;
title = newTitle;
firstName = newFirstName;
surname = newSurname;
searchText = newSearchText;
dateOfBirth = newDateOfBirth;
photo = newPhoto;
room= newRoom;
doctor = newDoctor;
nhs = newNhs;
residentBarcode = newResidentBarcode;
allergies = newAllergies;
additionalInformation = newAdditionalInformation;
}
public int ResidentID
{
get { return residentID; }
set { residentID = value; }
}
public string Title
{
get { return title; }
set { title = value; }
}
public string FirstName
{
get { return firstName; }
set { firstName = value; }
}
public string Surname
{
get { return surname; }
set { surname = value; }
}
public string SearchText
{
get { return searchText; }
set { searchText = value; }
}
public System.DateTime DateOfBirth
{
get { return dateOfBirth; }
set { dateOfBirth = value; }
}
public byte[] Photo
{
get { return photo; }
set { photo = value; }
}
public Room Room
{
get { return room; }
set { room = value; }
}
public Doctor Doctor
{
get { return doctor; }
set { doctor = value; }
}
public string NHS
{
get { return nhs; }
set { nhs = value; }
}
public string ResidentBarcode
{
get { return residentBarcode; }
set { residentBarcode = value; }
}
public string Allergies
{
get { return allergies; }
set { allergies = value; }
}
public string addtionalInformation{
get { return additionalInformation; }
set { additionalInformation = value; }
}
}
}
Looking at the way you've created your Resident:
Resident hello = new Resident();
ucMedicationCheckIn.SaveCheckedInMedication();
ResidentData.Update(hello);
ucMedicationCheckIn.HideDetails();
you probably haven't assigned it a doctor which is why it fails on this line:
command.Parameters.Add("#doctorID", SqlDbType.Int).Value = resident.Doctor.DoctorID;
You need to initialize the Doctor type
Edit*
After seeing your Resident class I can see that you haven't initialized Room either.
You could provide a constructor to initialize these to default values:
public Resident()
{
this.Doctor = new Doctor();
this.Room = new Room();
//etc...
}
Though to do anything meaningful you will probably want to set these up with actual data before saving.
That is because your Doctor and Room are not initialized anyhere:
Resident hello = new Resident();
hello.Doctor = new Doctor();
hello.Room = new Room();
but that update will probably fail as there is no meaningful data in resident and rowsAffected will return 0 probably.
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).