Update wingridview with BindingList - c#

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;

Related

How can I bind label content with value from query?

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.

WCF Not implementing interface member

I am working on a wcf service that connects to database. I had debugged and tested my operation playerregistration and clubregistration. I then tried to test the get functions but i received the error:
Error 1 'WebApplication1.ADOService' does not implement interface member 'WebApplication1.IADOService.newMembership(WebApplication1.playerDetails, WebApplication1.playerDetails, WebApplication1.clubDetails, WebApplication1.memberDetails)' C:\Users\Daniel\Documents\Visual Studio 2013\Projects\Prac4\WebApplication1\ADOService.svc.cs 14 18 WebApplication1
following the error I attempted to remove the get functions however the error remains. Below is the service code
public class ADOService : IADOService
{
public string playerRegistration(playerDetails playerInfo)
{
string Message;
using (SqlConnection conn = new SqlConnection("Data Source=(LocalDB)\\v11.0;AttachDbFilename=c:\\Users\\Daniel\\documents\\visual studio 2013\\Projects\\Prac4\\WebApplication1\\App_Data\\ADODatabase.mdf;Integrated Security=True"))
{
conn.Open();
using (var cmd = new SqlCommand("INSERT into Player(pid, pfname, plname, pphone, paddress, pdob) VALUES (#pid, #pfname, #plname, #pphone, #paddress, #pdob)", conn))
{
cmd.Parameters.AddWithValue("#pid", playerInfo.Pid);
cmd.Parameters.AddWithValue("#pfname", playerInfo.Pfname);
cmd.Parameters.AddWithValue("#plname", playerInfo.Plname);
cmd.Parameters.AddWithValue("#pphone", playerInfo.Pphone);
cmd.Parameters.AddWithValue("#paddress", playerInfo.Paddress);
cmd.Parameters.AddWithValue("#pdob", playerInfo.Pdob);
int result = cmd.ExecuteNonQuery();
if (result == 1)
{
Message = playerInfo.Pid + " Details inserted successfully";
}
else
{
Message = playerInfo.Pid + " Details not inserted successfully";
}
conn.Close();
return Message;
}
}
}
public string clubRegistration(clubDetails clubInfo)
{
string Message;
using (SqlConnection conn = new SqlConnection("Data Source=(LocalDB)\\v11.0;AttachDbFilename=c:\\Users\\Daniel\\documents\\visual studio 2013\\Projects\\Prac4\\WebApplication1\\App_Data\\ADODatabase.mdf;Integrated Security=True"))
{
conn.Open();
using (var cmd = new SqlCommand("INSERT into Club(cid, cname, cfounded, cworldranking) VALUES (#cid, #cname, #cfounded, #cworldranking)", conn))
{
cmd.Parameters.AddWithValue("#cid", clubInfo.Cid);
cmd.Parameters.AddWithValue("#cname", clubInfo.Cname);
cmd.Parameters.AddWithValue("#cfounded", clubInfo.Cfounded);
cmd.Parameters.AddWithValue("#cworldranking", clubInfo.Cworldranking);
int result = cmd.ExecuteNonQuery();
if (result == 1)
{
Message = clubInfo.Cname + " Details inserted successfully";
}
else
{
Message = clubInfo.Cname + " Details not inserted successfully";
}
conn.Close();
return Message;
}
}
}
public List<playerDetails> getplayerInfo(string pfname, string plname)
{
List<playerDetails> playerDetails = new List<playerDetails>();
{
using (SqlConnection conn = new SqlConnection("Data Source=(LocalDB)\\v11.0;AttachDbFilename=c:\\Users\\Daniel\\documents\\visual studio 2013\\Projects\\Prac4\\WebApplication1\\App_Data\\ADODatabase.mdf;Integrated Security=True"))
{
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM Player WHERE pfname LIKE '%'+#pfname+'%' AND plname LIKE '%'+#plname+'%'", conn);
cmd.Parameters.AddWithValue("#pfname", pfname);
cmd.Parameters.AddWithValue("#plname", plname);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
playerDetails playerInfo = new playerDetails();
playerInfo.Pid = Convert.ToInt32(dt.Rows[i]["Pid"].ToString());
playerInfo.Pfname = dt.Rows[i]["Pfname"].ToString();
playerInfo.Plname = dt.Rows[i]["Plname"].ToString();
playerInfo.Pphone = Convert.ToInt32(dt.Rows[i]["Pphone"].ToString());
playerInfo.Paddress = dt.Rows[i]["Paddress"].ToString();
playerInfo.Pdob = DateTime.Parse(dt.Rows[i]["Pdob"].ToString());
playerDetails.Add(playerInfo);
}
}
conn.Close();
}
return playerDetails;
}
}
public List<clubDetails> getclubInfo(string cname)
{
List<clubDetails> clubDetails = new List<clubDetails>();
{
using (SqlConnection conn = new SqlConnection("Data Source=(LocalDB)\\v11.0;AttachDbFilename=c:\\Users\\Daniel\\documents\\visual studio 2013\\Projects\\Prac4\\WebApplication1\\App_Data\\ADODatabase.mdf;Integrated Security=True"))
{
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM Player WHERE cname LIKE '%'+#cname+'%'", conn);
cmd.Parameters.AddWithValue("#cname", cname);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
clubDetails clubInfo = new clubDetails();
clubInfo.Cid = Convert.ToInt32(dt.Rows[i]["Cid"].ToString());
clubInfo.Cname = dt.Rows[i]["Cname"].ToString();
clubInfo.Cfounded = DateTime.Parse(dt.Rows[i]["Cfounded"].ToString());
clubInfo.Cworldranking = Convert.ToInt32(dt.Rows[i]["Cworldranking"].ToString());
clubDetails.Add(clubInfo);
}
}
conn.Close();
}
return clubDetails;
}
}}}
And Iservice code
[ServiceContract]
public interface IADOService
{
[OperationContract]
string playerRegistration(playerDetails playerInfo);
[OperationContract]
string clubRegistration(clubDetails clubInfo);
[OperationContract]
List<playerDetails> getplayerInfo(string pfname, string plname);
[OperationContract]
List<clubDetails> getclubInfo(string cname);
[OperationContract]
string newMembership(playerDetails pfname, playerDetails plname, clubDetails cname, memberDetails memberstart);
}
[DataContract]
public class playerDetails
{
int pid;
string pfname;
string plname;
int pphone;
string paddress;
DateTime pdob;
[DataMember]
public int Pid
{
get { return pid; }
set { pid = value; }
}
[DataMember]
public string Pfname
{
get { return pfname; }
set { pfname = value; }
}
[DataMember]
public string Plname
{
get { return plname; }
set { plname = value; }
}
[DataMember]
public int Pphone
{
get { return pphone; }
set { pphone = value; }
}
[DataMember]
public string Paddress
{
get { return paddress; }
set { paddress = value; }
}
[DataMember]
public DateTime Pdob
{
get { return pdob; }
set { pdob = value; }
}
}
[DataContract]
public class clubDetails
{
int cid;
string cname;
DateTime cfounded;
int cworldranking;
[DataMember]
public int Cid
{
get { return cid; }
set { cid = value; }
}
[DataMember]
public string Cname
{
get { return cname; }
set { cname = value; }
}
[DataMember]
public DateTime Cfounded
{
get { return cfounded; }
set { cfounded = value; }
}
[DataMember]
public int Cworldranking
{
get { return cworldranking; }
set { cworldranking = value; }
}
}
[DataContract]
public class memberDetails
{
int mid;
DateTime memberstart;
DateTime memberend;
int gamesplayed;
[DataMember]
public int Mid
{
get { return mid; }
set { mid = value; }
}
[DataMember]
public DateTime Memberstart
{
get { return memberstart; }
set { memberstart = value; }
}
[DataMember]
public DateTime Memberend
{
get { return memberend; }
set { memberend = value; }
}
[DataMember]
public int Gamesplayed
{
get { return gamesplayed; }
set { gamesplayed = value; }
}
}
}
I am assuming that the get functions are the cause of the problem but not sure how to address the error.
You've defined the following methods in your interface:
string playerRegistration(playerDetails playerInfo);
string clubRegistration(clubDetails clubInfo);
List<playerDetails> getplayerInfo(string pfname, string plname);
List<clubDetails> getclubInfo(string cname);
string newMembership(playerDetails pfname, playerDetails plname, clubDetails cname, memberDetails memberstart);
But only implemented four of them:
playerRegistration
clubRegistration
getplayerInfo
getclubInfo
You haven't actually implemented newMembership in the ADOService class.

Object reference not set to an instance of an object while Adding Parameter

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.

Three-tier architecture implementation in Windows form application

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).

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.

Categories