I am facing problem while i am inserting new record from GUI part to database table. I have created database table Patient with id, name, age etc....id is identity primary key. My problem is while i am inserting duplicate name in table the control should go to else part, and display the message like...This name is already exits, pls try with another name...
but in my coding not getting..... Here is all the code...pls somebody point me out whats wrong or how do this???
GUILayer:
protected void BtnSubmit_Click(object sender, EventArgs e)
{
if (!Page.IsValid)
return;
int intResult = 0;
string name = TxtName.Text.Trim();
int age = Convert.ToInt32(TxtAge.Text);
string gender;
if (RadioButtonMale.Checked)
{
gender = RadioButtonMale.Text;
}
else
{
gender = RadioButtonFemale.Text;
}
string city = DropDownListCity.SelectedItem.Value;
string typeofdisease = "";
foreach (ListItem li in CheckBoxListDisease.Items)
{
if (li.Selected)
{
typeofdisease += li.Value;
}
}
typeofdisease = typeofdisease.TrimEnd();
PatientBAL PB = new PatientBAL();
PatientProperty obj = new PatientProperty();
obj.Name = name;
obj.Age = age;
obj.Gender = gender;
obj.City = city;
obj.TypeOFDisease = typeofdisease;
try
{
intResult = PB.ADDPatient(obj);
if (intResult > 0)
{
lblMessage.Text = "New record inserted successfully.";
TxtName.Text = string.Empty;
TxtAge.Text = string.Empty;
RadioButtonMale.Enabled = false;
RadioButtonFemale.Enabled = false;
DropDownListCity.SelectedIndex = 0;
CheckBoxListDisease.SelectedIndex = 0;
}
else
{
lblMessage.Text = "Name [<b>" + TxtName.Text + "</b>] alredy exists, try another name";
}
}
catch (Exception ex)
{
lblMessage.Text = ex.Message.ToString();
}
finally
{
obj = null;
PB = null;
}
}
BAL layer:
public class PatientBAL
{
public int ADDPatient(PatientProperty obj)
{
PatientDAL pdl = new PatientDAL();
try
{
return pdl.InsertData(obj);
}
catch
{
throw;
}
finally
{
pdl=null;
}
}
}
DAL layer:
public class PatientDAL
{
public string ConString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
public int InsertData(PatientProperty obj)
{
SqlConnection con = new SqlConnection(ConString);
con.Open();
SqlCommand com = new SqlCommand("LoadData",con);
com.CommandType = CommandType.StoredProcedure;
try
{
com.Parameters.AddWithValue("#Name", obj.Name);
com.Parameters.AddWithValue("#Age",obj.Age);
com.Parameters.AddWithValue("#Gender",obj.Gender);
com.Parameters.AddWithValue("#City", obj.City);
com.Parameters.AddWithValue("#TypeOfDisease", obj.TypeOFDisease);
return com.ExecuteNonQuery();
}
catch
{
throw;
}
finally
{
com.Dispose();
con.Close();
}
}
}
Property Class:
public class PatientProperty
{
private string name;
private int age;
private string gender;
private string city;
private string typedisease;
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
public int Age
{
get
{
return age;
}
set
{
age = value;
}
}
public string Gender
{
get
{
return gender;
}
set
{
gender = value;
}
}
public string City
{
get
{
return city;
}
set
{
city = value;
}
}
public string TypeOFDisease
{
get
{
return typedisease;
}
set
{
typedisease = value;
}
}
}
This is my stored Procedure:
CREATE PROCEDURE LoadData
(
#Name varchar(50),
#Age int,
#Gender char(10),
#City char(10),
#TypeofDisease varchar(50)
)
as
insert into Patient(Name, Age, Gender, City, TypeOfDisease)values(#Name,#Age, #Gender, #City, #TypeofDisease)
GO
Are you sure your LoadData stored proc is doing an insert instead of an update?
looks like your throwing the error, so it jumps down to your catch block.
You'll need to handle the error coming back from PB.ADDPatient and not the value
Does the record duplicated in the database? I am afraid you did not add the unique constraint for Names in the database!
If this is the case, and you are using SQL Server, check this:
SQL Server 2005 How Create a Unique Constraint?
Related
i have ran into some problems with my insert function.
i am trying to make my the string listing_ID an auto increment int with no input needed, however when coding for the button submit i included all the inputs for all the other values but not listing_ID , this gave me the error below. below are all the images and these are the codes for the insert function.
public class Carlisting
{
private string _listID = "";
private string _car_model = "";
private string _brand_name = "";
private string _car_description = "";
private string _car_condition = "";
private string _price = "";
private string _inspection_date = "";
string _connStr = ConfigurationManager.ConnectionStrings["roadbnb.mdf"].ConnectionString;
public Carlisting(string listID, string car_model, string brand_name, string car_description, string car_condition, string price, string inspection_date)
{
_listID = listID;
_car_model = car_model;
_brand_name = brand_name;
_car_description = car_description;
_car_condition = car_condition;
_price = price;
_inspection_date = inspection_date;
}
public Carlisting()
{
}
public string listing_ID
{
get { return _listID; }
set { _listID = value; }
}
public string car_model
{
get { return _car_model; }
set { _brand_name = value; }
}
public string brand_name
{
get { return _brand_name; }
set { _brand_name = value; }
}
public string car_description
{
get { return _car_description; }
set { _car_description = value; }
}
public string car_condition
{
get { return _car_condition; }
set { _car_condition = value; }
}
public string price
{
get { return _price; }
set { _price = value; }
}
public string inspection_date
{
get { return _inspection_date; }
set { _inspection_date = value; }
}
protected void btn_submit_Click(object sender, EventArgs e)
{
int result = 0;
Carlisting car = new Carlisting(tb_model.Text, tb_brand.Text, tb_description.Text, dl_condition.Text, tb_price.Text, tb_date.Text);
result = car.ListingInsert();
if (result > 0)
{
Response.Write("<script>alert('You have succesfully added listing , PLease wait for approval');</script>");
}
else
{
Response.Write("<script>alert('Error : PLease contact helpdesk');</script>");
}
}
public int ListingInsert()
{
int result = 0;
string queryStr = "INSERT INTO Carlisting(car_model, brand_name, car_description, car_condition , price, inspection_date)"
+"VALUES (#car_model, #brand_name, #car_description, #car_condition, #price, #inspection_date)";
SqlConnection conn = new SqlConnection(_connStr);
SqlCommand cmd = new SqlCommand(queryStr, conn);
cmd.Parameters.AddWithValue("#car_model", this.car_model);
cmd.Parameters.AddWithValue("#brand_Name", this.brand_name);
cmd.Parameters.AddWithValue("#car_description", this.car_description);
cmd.Parameters.AddWithValue("#car_condition", this.car_condition);
cmd.Parameters.AddWithValue("#price", this.price);
cmd.Parameters.AddWithValue("#inspection_date", this.inspection_date);
conn.Open();
result += cmd.ExecuteNonQuery();
conn.Close();
return result;
}
Does anyone know how should fix it in order to get the results i wan? Thank you in advance
As per your screenshot, you are getting compilation error. To Fix it, create another constructor. Currently your code want to invoke constructor which does not take listId as parameter.
public Carlisting(string listID, string car_model, string brand_name, string car_description, string car_condition, string price, string inspection_date)
: this(car_model, brand_name, car_description, car_condition, price, inspection_date)
{
_listID = listID;
}
public Carlisting(string car_model, string brand_name, string car_description, string car_condition, string price, string inspection_date)
{
_car_model = car_model;
_brand_name = brand_name;
_car_description = car_description;
_car_condition = car_condition;
_price = price;
_inspection_date = inspection_date;
}
With above the 1st constructor invokes the another constructor with other required parameters. And for your code, the 2nd constructor will be invoked and you won't have compilation error.
I 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).
I just downloaded ObjectListView, and have an issue with populating it.
I got list of MyObject:
public class MyObject
{
public int Id { get; set; }
public int ParentId { get; set; }
public string Name { get; set; }
public int Data { get; set; }
public MyObject(int id, int parentId, string name, int data)
{
Id = id;
ParentId = parentId;
Name = name;
Data = data;
}
}
List<MyObject> list = List<MyObject>();
I need to populate a TreeListView with MyObject elements (Using TreeListView).
Also I need one column been filled with .Data property.
I can not populate it even as a list(all items on the same level) and without any columns, I've tried this:
this.myTreeListView.SetObjects(list);
and this:
this.myTreeListView.Roots = list;
But the tree is still empty, nothing has been populated, what am I doing wrong ? Please help.
You can find some useful "getting started" information regarding the TreeListView here. Make sure you understand and use that concept.
However, there is no mention that you also have to add at least one column (you can do this in the designer). So this might be your problem. The TreeListView tutorial assumes that you already know how to use the ObjectListView.
I suggest you also read the general getting started guide, especially the "mental gear shift" section.
The crucial part of using an ObjectListView is configuring it. Most of this configuration can be done within the IDE by setting properties on the ObjectListView itself or on the columns that are used within the list. Some configuration cannot be done through properties: these more complex configurations are done by installing delegates (more on this later). Once the columns and control are configured, putting it into action is simple.
Hope this helps.
this way i do it. here i am giving my full code. have a look and ask me if u have any confusion. thanks
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace WindowsApplication1
{
public partial class Form3 : Form
{
private List<Node> data;
public Form3()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
InitializeData();
FillTree();
}
private void InitializeData()
{
string connString = "Data Source=xxx.xx.xx.xx\\test;Initial Catalog=Test;User id=sa;Password=test;";
string sql = "USP_RefundRequested";
SqlConnection conn = new SqlConnection(connString);
data = new List<Node>();
try
{
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = new SqlCommand(sql, conn);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
DataSet ds = new DataSet();
da.Fill(ds);
DataTable dt = ds.Tables[0];
if (ds != null)
{
if (ds.Tables.Count > 0)
{
ds.Relations.Add("ParentChild",ds.Tables[0].Columns["JID"],
ds.Tables[1].Columns["CID"]);
DataRelation orderRelation = ds.Relations["ParentChild"];
foreach (DataRow order in ds.Tables[0].Rows)
{
//Console.WriteLine("Subtotals for Order {0}:", order["OrderNumber"]);
Node parent1 = new Node( order["JID"].ToString(), "", "","","");
foreach (DataRow oChild in order.GetChildRows(orderRelation))
{
//Console.WriteLine("Order Line {0}: {1}", orderDetail["OrderLineNumber"], string.Format("{0:C}", orderDetail["Price"]));
parent1.Children.Add(new Node("", oChild["EntryDate"].ToString(),
oChild["RefundDate"].ToString(),
oChild["ActionBy"].ToString(),
oChild["Comments"].ToString()
));
}
data.Add(parent1);
}
}
}
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex);
}
finally
{
conn.Close();
}
}
private void FillTree()
{
this.treeListView1.CanExpandGetter = delegate(object x) { return ((Node)x).Children.Count > 0; };
this.treeListView1.ChildrenGetter = delegate(object x) { return ((Node)x).Children; };
// create the tree columns and set the delegates to print the desired object proerty
BrightIdeasSoftware.OLVColumn JIDCol = new BrightIdeasSoftware.OLVColumn("Job ID", "JID");
JIDCol.AspectGetter = delegate(object x) { return ((Node)x).JID; };
BrightIdeasSoftware.OLVColumn EntryDatecol = new BrightIdeasSoftware.OLVColumn("Entry Date", "EntryDate");
EntryDatecol.AspectGetter = delegate(object x) { return ((Node)x).EntryDate; };
BrightIdeasSoftware.OLVColumn RefundDatecol = new BrightIdeasSoftware.OLVColumn("Refund Date", "RefundDate");
RefundDatecol.AspectGetter = delegate(object x) { return ((Node)x).RefundDate; };
BrightIdeasSoftware.OLVColumn ActionBycol2 = new BrightIdeasSoftware.OLVColumn("Action By", "ActionBy");
ActionBycol2.AspectGetter = delegate(object x) { return ((Node)x).ActionBy; };
BrightIdeasSoftware.OLVColumn Commentscol3 = new BrightIdeasSoftware.OLVColumn("Comments", "Comments");
Commentscol3.AspectGetter = delegate(object x) { return ((Node)x).Comments; };
// add the columns to the tree
this.treeListView1.Columns.Add(JIDCol);
this.treeListView1.Columns.Add(EntryDatecol);
this.treeListView1.Columns.Add(RefundDatecol);
this.treeListView1.Columns.Add(ActionBycol2);
this.treeListView1.Columns.Add(Commentscol3);
// set the tree roots
this.treeListView1.Roots = data;
treeListView1.Columns[1].Width = 142;
treeListView1.Columns[2].Width = 142;
treeListView1.Columns[3].Width = 179;
treeListView1.Columns[4].Width = 667;
treeListView1.Columns[treeListView1.Columns.Count - 1].Width = -2;
treeListView1.ExpandAll();
}
}
public class Node
{
public string _jid = "";
public string JID
{
get { return _jid; }
set { _jid = value; }
}
//public int _cid = 0;
//public int CID
//{
// get { return _cid; }
// set { _cid = value; }
//}
public string _entrydate;
public string EntryDate
{
get { return _entrydate; }
set { _entrydate = value; }
}
public string _refunddate;
public string RefundDate
{
get { return _refunddate; }
set { _refunddate = value; }
}
public string _actionby = "";
public string ActionBy
{
get { return _actionby; }
set { _actionby = value; }
}
public string _comments = "";
public string Comments
{
get { return _comments; }
set { _comments = value; }
}
public List<Node> _Children = null;
public List<Node> Children
{
get { return _Children; }
set { _Children = value; }
}
public Node(string JID, string EntryDate, string RefundDate, string ActionBy, string Comments)
{
this.JID = JID;
//this.CID = CID;
this.EntryDate = EntryDate;
this.RefundDate = RefundDate;
this.ActionBy = ActionBy;
this.Comments = Comments;
this.Children = new List<Node>();
}
}
}
ALTER PROC USP_RefundRequested
AS
BEGIN
;WITH Hierarchy AS
(
SELECT DISTINCT JID
,CAST(NULL AS DATETIME) EntryDate
,CAST(NULL AS DATETIME) RefundDate
,CAST(NULL AS VARCHAR(MAX)) Comments
,CAST(NULL AS BIT) Refund
,CAST(NULL AS VARCHAR(30)) ActionBy
,nLevel = 1
,0 AS CID
FROM refundrequested
UNION ALL
SELECT CAST(NULL AS INT) JID
,E.EntryDate
,E.RefundDate
,E.Comments
,E.Refund
,E.ActionBy
,H.nLevel+1
,H.JID AS CID
FROM refundrequested E
JOIN Hierarchy H ON E.JID = H.JID
)
--SELECT *
--FROM Hierarchy WHERE CID=0
--ORDER BY COALESCE(JID, CID) DESC, nLevel
SELECT * into #tmpHierarchy FROM Hierarchy
SELECT JID,EntryDate,RefundDate,ActionBy,Comments,CID
FROM tmpHierarchy WHERE CID=0
ORDER BY COALESCE(JID, CID) DESC, nLevel
SELECT JID,EntryDate,RefundDate,ActionBy,Comments,CID
FROM tmpHierarchy WHERE CID>0
ORDER BY COALESCE(JID, CID) DESC, nLevel
drop table #tmpHierarchy
END
go
I am writing code in C# where I want to select data in datagrid from multiple tables with a relation... Here I have a Client & Item_Configuration as parent table and Item_Order as child table which has the foreign keys from Client and Item_Configuration, I just want to fetch data from all three tables and display on a datagrid
My stored procedure is:
ALTER PROC [dbo].[Full_SP]
#clientName varchar(50) = null,
#itemName varchar(50) = null,
#clientId_FK varchar(50) = null,
#operation int
AS
BEGIN
SET NOCOUNT ON;
if #operation = 2
BEGIN
SELECT
Client.clintName, Item_Configuration.itemName,
Item_Order.orderId, Item_Order.orderDate, Item_Order.quantity,
Item_Order.status, Item_Order.totalPrice
FROM
Item_Order
INNER JOIN
Client ON Item_Order.clintId_FK = Client.clientId
JOIN
Item_Configuration ON Item_Order.itemId_FK = Item_Configuration.itemId
END
END
And my function of search to data grid is in C# i.e.
private void btnSrchFull_Click(object sender, EventArgs e)
{
SqlConnection conn1 = new SqlConnection();
try
{
conn1.ConnectionString = "server=.\\ms2k5;database=Info_Connect;Trusted_Connection=true";
conn1.Open();
SqlCommand selectFull = new SqlCommand("Full_SP", conn1);
selectFull.CommandType = CommandType.StoredProcedure;
selectFull.Parameters.Add("#operation", SqlDbType.VarChar);
selectFull.Parameters["#operation"].Value = 2;
SqlDataReader myReader = selectFull.ExecuteReader();
List<FullFill> list = new List<FullFill>();
while (myReader.Read())
{
if (myReader.HasRows)
{
FullFill fullfill = new FullFill();
fullfill = MapFullfill(myReader, fullfill);
list.Add(fullfill);
}
}
myReader.NextResult();
foreach (FullFill ffll in list)
{
if (myReader.Read() && myReader.HasRows)
{
MapClient(myReader, ffll);
}
}
myReader.NextResult();
foreach (FullFill ffll1 in list)
{
if (myReader.Read() && myReader.HasRows)
{
MapItem(myReader, ffll1);
}
}
dataGridView1.DataSource = list;
double totPrice = 0;
for (int i = 0; i < dataGridView1.RowCount; i++)
{
totPrice = totPrice +
Convert.ToDouble(dataGridView1.Rows[i].Cells[5].Value);
totCost.Text = totPrice.ToString();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.StackTrace + MessageBoxIcon.Error);
}
finally
{
if (conn1.State != ConnectionState.Closed)
{
conn1.Close();
}
}
}
private FullFill MapItem(SqlDataReader myReader, FullFill itemName)
{
itemName.ItemName =myReader["itemName"].ToString();
return itemName;
}
private FullFill MapClient(SqlDataReader myReader, FullFill clientName)
{
clientName.ClientName = myReader["clientName"].ToString();
return clientName;
}
private FullFill MapFullfill(SqlDataReader myReader, FullFill fullfill)
{
fullfill.OrderNo = myReader["orderId"].ToString();
fullfill.OrderDate = Convert.ToDateTime(myReader["orderDate"]);
fullfill.Quantity = Convert.ToInt32(myReader["quantity"]);
fullfill.Status = myReader["status"].ToString();
fullfill.TotalPrice = Convert.ToDouble(myReader["totalPrice"]);
return fullfill;
}
and I created a class for property i.e.
class FullFill
{
public string orderNo;
public string clientName;
public DateTime orderDate;
public string itemName;
public int quantity;
public double totCost;
public string status;
public string OrderNo { get { return orderNo; } set { orderNo = value; } }
public string ClientName { get { return clientName; } set { clientName = value; } }
public DateTime OrderDate { get { return orderDate; } set { orderDate = value; } }
public string ItemName { get { return itemName; } set { itemName = value; } }
public int Quantity { get { return quantity; } set { quantity = value; } }
public double TotalPrice { get { return totCost; } set { totCost = value; } }
public string Status { get { return status; } set { status = value; } }
}
}
The problem is that I am only able to find data from child table(Item_Order) I am not getting data from parent Tables.