WCF Not implementing interface member - c#

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.

Related

How To Identify button click of a node in dataTreeListView1 in C#

I have dataTreeListView named dataTreeListView1 i wish to get the name of the node which i clicked can any one please help me to do this
in the above picture if i click yes i wish to get yes on messagebox
what i tried to do is
private void dataTreeListView1_AfterSelect(object sender, EventArgs e)
{
MessageBox.Show("hello");
}
and the node are loaded dynamically means they are from database.
List<Class3> list = new List<Class3>();
list = Class3.GetList(startDate, endDate, con);
this.dataTreeListView1.ParentKeyAspectName = "ParentId";
this.dataTreeListView1.RootKeyValueString = "NUll";
BrightIdeasSoftware.OLVColumn col = new BrightIdeasSoftware.OLVColumn();
col.Width = 10;
dataTreeListView1.DataSource = list;
foreach (ColumnHeader column in this.dataTreeListView1.Columns)
{
column.Width = 140 + 140 + this.dataTreeListView1.SmallImageSize.Width;
}
this.dataTreeListView1.Columns.RemoveByKey("Id");
this.dataTreeListView1.Columns.RemoveByKey("ParentId");
this is how i show data in datatreelist view
public Class3()
{
this.xName = "";
this.xId = "";
this.xParentId = "";
this.xcredit = 0.0M;
this.xdebit = 0.0M;
this.xx = 0.0M;
this.xy = 0.0M;
}
public String Ledger
{
get { return this.xName; }
set { this.xName = value; }
}
public String Id
{
get { return this.xId; }
set { this.xId = value; }
}
public String ParentId
{
get { return this.xParentId; }
set { this.xParentId = value; }
}
public Decimal Credit
{
get { return this.xcredit; }
set { this.xcredit = value; }
}
public Decimal Debit
{
get { return this.xdebit; }
set { this.xdebit = value; }
}
public decimal x
{
get { return this.xx; }
set { this.xx = value; }
}
public decimal y
{
get { return this.xy; }
set { this.xy = value; }
}
public static List<Class3> GetList(DateTime startDate, DateTime endDate, SqlConnection con)
{
List<Class3> oList = new List<Class3>();
Buisiness b = new Buisiness();
try
{
decimal totalcredit = 0;
decimal totaldebit = 0;
con.Open();
// // Make sql readable
DataTable dt = new DataTable();
string sql = #"Select Ledger.LedId,Ledger.LedName,Ledger.MasterLedger from Ledger where Ledger.Date >= #prmStartDate and Ledger.Date <= #prmEndDate group by Ledger.MasterLedger,Ledger.LedId,Ledger.LedName";
// wrap IDisposable (SqlCommand) into using
using (SqlCommand cmd = new SqlCommand(sql, con))
{
cmd.Parameters.Add("#prmStartDate", SqlDbType.DateTime).Value = startDate;
cmd.Parameters.Add("#prmEndDate", SqlDbType.DateTime).Value = endDate;
SqlDataReader da = cmd.ExecuteReader();
while (da.Read())
{
Class3 oClass = new Class3();
oClass.Ledger = da["LedName"].ToString();
oClass.Id = da["LedId"].ToString();
oClass.ParentId = da["MasterLedger"].ToString();
Dictionary<string, decimal> d = b.findclosingbalanceofledger(da["LedId"].ToString());
/* if (da["MasterLedger"].ToString() == "NUll")
{
oClass.Debit = findsumofallchilds(da["LedId"].ToString(), con, startDate, endDate);
}
else
{*/
if (d.FirstOrDefault().Key == "debit")
{
d.FirstOrDefault().Value.ToString();
d.FirstOrDefault().Value.ToString();
totaldebit = totaldebit + d.FirstOrDefault().Value;
oClass.Debit = d.FirstOrDefault().Value;
}
else if (d.FirstOrDefault().Key == "credit")
{
d.FirstOrDefault().Value.ToString();
totalcredit = totalcredit + d.FirstOrDefault().Value;
oClass.Credit = d.FirstOrDefault().Value;
}
/* }*/
oList.Add(oClass);
}
}
con.Close();
}
catch (Exception exe)
{
MessageBox.Show(exe.Message);
}
finally
{
con.Close();
}
return oList;
}
i have changed my code this
private void dataTreeListView1_AfterSelect(object sender, EventArgs e)
{
MessageBox.Show("hello");
}
to
private void dataTreeListView1_CellClick(object sender, CellClickEventArgs e)
{
MessageBox.Show("helo");
}
but no change

Update wingridview with BindingList

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;

Binding dropdownlist with generic list in 3-tier architecture

/*data access layer */
public DataSet getdata(string procedurename, SqlParameter[] param)
{
try
{
SqlCommand command;
command = new SqlCommand(procedurename, connection);
command.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adapter = new SqlDataAdapter(command);
DataSet set = new DataSet();
if (param != null)
{
for (int i = 0; i < param.Length; i++)
{
command.Parameters.Add(param[i]);
}
}
adapter.Fill(set);
return set;
}
catch (Exception ex)
{
throw ex;
}
finally
{
closeConnection();
}
}
Middle Tier:
public class dropdownbind
{
private string _itemName;
private int _itemvalue;
public int Itemvalue
{
get { return _itemvalue; }
set { _itemvalue = value; }
}
public string ItemName
{
get { return _itemName; }
set { _itemName = value; }
}
public List<dropdownbind> getDepartment()
{
DBlist obj = new DBlist();
DataSet ds = obj.getdata("str_getdepartment",null);
List<dropdownbind> departments = new List<dropdownbind>();
foreach (DataRow orow in ds.Tables[0].Rows)
{
dropdownbind dlist = new dropdownbind();
dlist.ItemName = orow["deparment_name"].ToString();
dlist.Itemvalue = int.Parse(orow["id"].ToString());
departments.Add(dlist);
}
return departments;
}
}
UI:-
protected void BindDdlList()
{
dropdownbind dlist = new dropdownbind();
List<dropdownbind> departments = dlist.getDepartment();
ddlEmpDepatment.DataSource = departments;
ddlEmpDepatment.DataTextField = dlist.ItemName;
ddlEmpDepatment.DataValueField = dlist.Itemvalue.ToString();
ddlEmpDepatment.DataBind();
}
i am trying to bind departments to dropdownlist using 3-tier architecture.
but this code is not working, it shows middletier.dropdownbind in text field.
You need to correct the DataTextField & DataValueField properties like this:-
ddlEmpDepatment.DataValueField = "Itemvalue";
ddlEmpDepatment.DataTextField = "ItemName";
You are specifying the property name rather you need to specify the property name as string.

Recursion to display parent child values in datagridview c# winforms

Using Recursion I Want to Display the list of Contents to the datagridview in c# winforms.I tried by the below But as a result in datagridview Only Parent values displaying no Child Values Displayed
public class PageItem
{
public int Id { get; set; }
public int ParentId { get; set; }
public string MenuText { get; set; }
public List<PageItem> Childs { get; set; }
}
Conditions:-
public List<PageItem> GetPageItems()
{
List<PageItem> pageItems = new List<PageItem>();
SqlCeConnection conn = new SqlCeConnection(#"Data
Source=D:\database\Employee.mdf;");
SqlCeCommand cmd = new SqlCeCommand("SELECT Id, ParentId, MenuTitle
FROM Page", conn);
conn.Open();
SqlCeDataReader rdr = cmd.ExecuteReader();
var allItems = new List<PageItem>();
while (rdr.Read())
{
var item = (new PageItem()
{
Id = Convert.ToInt32(rdr["Id"]),
ParentId = Convert.ToInt32(rdr["ParentId"]),
MenuText = rdr["MenuTitle"].ToString()
});
allItems.Add(item);
var parent = allItems.Where(pi => pi.Id == item.ParentId).SingleOrDefault();
if (parent == null)
{
pageItems.Add(item);
}
else
{
if (parent.Childs == null)
parent.Childs = new List<PageItem>();
parent.Childs.Add(item);
}
}
rdr.Close();
conn.Close();
return pageItems;
}
Form Load:-
private void Form1_Load(object sender, EventArgs e)
{
GetPageItems();
this.dataGridView1.DataSource = GetPageItems();
this.comboBox1.DataSource = GetPageItems();
this.comboBox1.DisplayMember = "MenuText";
this.comboBox1.ValueMember = "ParentId";
}
From the above code I got an output like this:-
parent 0
parent 1
parent 2
parent 3
I Need an Output Like this:-
Parent 0
Child 1
Child 2
Child 3
Child 3.1
Child 3.2
Child 3.3
Parent 1
Parent 2
Parent 3
Thank You..
Finally I Got Answer For the Above Question Using Recursion .If Anybody Needs make Use of it Thank You:-
public class Student
{
public int ID { get; set; }
public int ParentID { get; set; }
public string Title { get; set; }
}
public class Parent
{
public int pID { get; set; }
public int pParentID { get; set; }
public string pTitle { get; set; }
}
public class OutPut
{
public int mID { get; set; }
public int mParentID { get; set; }
public string mTitle { get; set; }
}
public class SubOutPut
{
public int SubsmID { get; set; }
public int SubsmParentID { get; set; }
public string SubsmTitle { get; set; }
}
Form Load
public static List<SubOutPut> ChildList = new List<SubOutPut>();
private void Form3_Load(object sender, EventArgs e)
{
List<Student> std = loaddataFull();
List<Parent> prnt = loaddataParent();
List<OutPut> MenuItems = new List<OutPut>();
foreach (Parent id in prnt)
{
int pid=Convert.ToInt32(id.pID);
//Adding Parent Values to the List
List<SubOutPut> SubMenuItems = new List<SubOutPut>();
MenuItems.Add(new OutPut()
{
mID=Convert.ToInt32(id.pID),
mParentID=Convert.ToInt32(id.pParentID),
mTitle=Convert.ToString(id.pTitle),
});
SubMenuItems = GetChildrens(pid);
foreach (SubOutPut Add in SubMenuItems)
{
MenuItems.Add(new OutPut()
{
mID = Convert.ToInt32(Add.SubsmID),
mParentID = Convert.ToInt32(Add.SubsmParentID),
mTitle = Convert.ToString(Add.SubsmTitle)
});
}
SubMenuItems.Clear();
}
dataGridView1.DataSource = MenuItems;
foreach (var item in MenuItems)
{
listView1.Items.Add(item.mID.ToString());
listView1.Items.Add(item.mParentID.ToString());
listView1.Items.Add(item.mTitle.ToString());
listView1.View = View.Tile;
}
dataGridView2.DataSource = loaddataParent();
}
Loading all datas from database
public List<Student> loaddataFull()
{
List<Student> student = new List<Student>();
SqlConnection conn = new SqlConnection(#"Data Source=ADMIN-PC\SQLEXPRESS;Initial Catalog=test;Integrated Security=true");
SqlCommand cmd = new SqlCommand("select * from testing", conn);
SqlDataReader dr;
try
{
conn.Open();
dr = cmd.ExecuteReader();
while (dr.Read())
{
student.Add(new Student()
{
ID = dr.GetInt32(dr.GetOrdinal("id")),
ParentID = dr.GetInt32(dr.GetOrdinal("pid")),
Title = dr.GetString(dr.GetOrdinal("title"))
});
}
dr.Close();
}
catch (Exception exp)
{
throw;
}
finally
{
conn.Close();
}
return student;
}
Load Only The Parent Values:-
public List<Parent> loaddataParent()
{
List<Parent> parent = new List<Parent>();
SqlConnection conn = new SqlConnection(#"Data Source=ADMIN-PC\SQLEXPRESS;Initial Catalog=test;Integrated Security=true");
SqlCommand cmd = new SqlCommand("select * from testing where pid=0", conn);
SqlDataReader dr;
try
{
conn.Open();
dr = cmd.ExecuteReader();
while (dr.Read())
{
parent.Add(new Parent()
{
pID = dr.GetInt32(dr.GetOrdinal("id")),
pParentID = dr.GetInt32(dr.GetOrdinal("pid")),
pTitle = dr.GetString(dr.GetOrdinal("title"))
});
}
dr.Close();
}
catch (Exception exp)
{
throw;
}
finally
{
conn.Close();
}
return parent;
}
And Here Comes The Recursion Method:-
public string gg = " ";
public List<SubOutPut> GetChildrens(int ID)
{
List<Student> std = loaddataFull();
foreach (Student Child in std)
{
if (Child.ParentID == ID)
{
ChildList.Add(new SubOutPut()
{
SubsmID = Convert.ToInt32(Child.ID),
SubsmParentID = Convert.ToInt32(Child.ParentID),
SubsmTitle = Convert.ToString(gg + Child.Title)
});
gg = gg+gg;
GetChildrens(Child.ID);
gg = " ";
}
}
return ChildList;
}
Thank You:---

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.

Categories