How to populate BrightIdeasSoftware.TreeListView ? - c#

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

Related

EF6 duplicate entries on related entities

Ok, so I'm really frustrated with the duplication issues of EF6. I have searched the forum extensively and tried different things, but I can't seem to figure this one out.
My base model is a trainingprogram, that consists of many blocks, which in turn hold a list of circuits. Every circuit holds a number of exercisesets and progressions for each exercise. All the relevant parts of the model are in the minimal workin example below.
I have a controller that I use to persist training programs to the DB. Whenever I call dbcontext.SaveChanges(), my database i populated with duplicates of the related entities, although I have tried setting the state to unchanged, attaching the enities to the context and what not. Pretty much everything gets duplicated - exercises, categories and progressionschemes.
This is really a blocker, so any help is appreciated.
[HttpPost]
[Route("Add")]
public HttpResponseMessage AddProgram(TrainingProgram program)
{
int id = -1;
try
{
using (var dbcontext = new ApplicationDbContext())
{
foreach (TrainingBlock b in program.Blocks)
foreach (ExercisePairing c in b.Circuits)
{
foreach (ProgressionScheme ps in c.Progressions.Select(x => x.Progression).Distinct().ToList())
{
var ep = dbcontext.Progressions.FirstOrDefault(p => p.Name == ps.Name && p.Id == ps.Id);
if (ep is null)
dbcontext.Progressions.Attach(ps);
//dbcontext.Entry(ps).State = EntityState.Unchanged;// Attach(ps);
}
foreach (Exercise s in c.Sets.Select(x => x.Exercise).Distinct().ToList())
{
//dbcontext.Entry(s).State = EntityState.Unchanged;
//dbcontext.Entry(s.Category).State = EntityState.Unchanged;
dbcontext.ExerciseCategories.Attach(s.Category);
dbcontext.Exercises.Attach(s);
}
}
dbcontext.TrainingPrograms.AddOrUpdate(program);
dbcontext.SaveChanges();
id = program.Id;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return new HttpResponseMessage(HttpStatusCode.BadRequest);
}
return Request.CreateResponse(HttpStatusCode.OK, id);
}
public class ExercisePairing:BaseClass
{
private List<ExerciseSet> sets = new List<ExerciseSet>();
private List<ProgressionForExercise> progressions = new List<ProgressionForExercise>();
private int id;
...
...
}
}
public class ProgressionForExercise:BaseClass
{
public int Id { get; set; }
private Exercise exercise;
public int ExerciseId { get; set; }
public int ProgressionId { get; set; }
[ForeignKey("ExerciseId")]
public Exercise Exercise
{
get => exercise;
set
{
exercise = value;
ExerciseId = exercise.Id;
}
}
private ProgressionScheme progression;
[ForeignKey("ProgressionId")]
public ProgressionScheme Progression
{
get =>progression ;
set
{
progression = value;
ProgressionId = progression.Id;
}
}
}
public class Exercise : BaseClass
{
private int id;
private string name;
private string description;
private string videourl;
private ExerciseCategory category;
public int CategoryId { get; set; }
[ForeignKey("CategoryId")]
public ExerciseCategory Category
{
get => category;
set
{
category = value;
OnPropertyChanged();
}
}
public int Id
{
get => id;
set
{
id = value;
OnPropertyChanged();
}
}
...
...
}
public class ExerciseCategory:BaseClass
{
private string name;
private int id;
[Key]
public int Id
{
get => id;
set
{
id = value;
OnPropertyChanged();
}
}
public string Name
{
get => name;
set
{
name = value;
OnPropertyChanged();
}
}
...
...
}
public class ProgressionScheme:BaseClass
{
private int id;
private string name;
private string description;
public int Id
{
get => id;
set
{
id = value;
OnPropertyChanged();
}
}
public string Name
{
get => name;
set
{
name = value;
OnPropertyChanged();
}
}
...
...
}
EDIT
I now solved the issue by basically re-wrtiting my controller code like so:
[HttpPost]
[Route("Add")]
public HttpResponseMessage AddProgram(TrainingProgram program)
{
int id = -1;
try
{
using (var dbcontext = new ApplicationDbContext())
{
TrainingProgram tp = new TrainingProgram();
tp.Title = program.Title;
tp.Remarks = program.Remarks;
tp.CreationDate = program.CreationDate;
tp.Creator = program.Creator;
tp.Blocks = new List<TrainingBlock>();
foreach (TrainingBlock b in program.Blocks)
{
TrainingBlock tb = new TrainingBlock();
tb.Title = b.Title;
tb.Remarks = b.Remarks;
tb.Circuits = new List<ExercisePairing>();
foreach (ExercisePairing c in b.Circuits)
{
ExercisePairing ep = new ExercisePairing();
ep.Sets = new List<ExerciseSet>();
foreach(ExerciseSet s in c.Sets)
{
ExerciseSet es = new ExerciseSet();
Exercise ex = dbcontext.Exercises.Find(s.Exercise.Id);
es.Exercise = ex;
ExerciseCategory ec = dbcontext.ExerciseCategories.Find(s.Exercise.Category.Id);
es.Exercise.Category = ec;
es.Reps = s.Reps;
es.Intensity = s.Intensity;
es.Unit = s.Unit;
ep.Sets.Add(es);
}
ep.Progressions = new List<ProgressionForExercise>();
foreach (ProgressionForExercise pro in c.Progressions)
{
Exercise ex = dbcontext.Exercises.Find(pro.Exercise.Id);
ProgressionScheme ps = dbcontext.Progressions.Find(pro.Progression.Id);
ProgressionForExercise p4e = new ProgressionForExercise();
p4e.Exercise = ex;
p4e.Progression = ps;
ep.Progressions.Add(p4e);
}
tb.Circuits.Add(ep);
}
tp.Blocks.Add(tb);
}
dbcontext.TrainingPrograms.AddOrUpdate(tp);
dbcontext.SaveChanges();
id = tp.Id;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return new HttpResponseMessage(HttpStatusCode.BadRequest);
}
return Request.CreateResponse(HttpStatusCode.OK, id);
}
So in essence, I am avoiding the duplicates by only using the very objects that are present in the Context. Although this works, I am not sure if I am happy with that. If a simple CRUD peration takes that much code, I fail to see the upside of using EF VS simply using an SQL insert statement, which would be much more efficient in this case IMHO. Also, why does EF ignore the primary keys and insist on using its wn instances of my enitities? All of this is very strange.

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

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.

C# Dapper problems with IN statement using string array

I have an string array (query.Tags) for filter a list of values and each time, procces just take the first value of string array during the query execution.
I tried several combinations but nothing changed. Of course, I tested all of these SQL statements in SQL SERVER View.
Can you tell me what I doing wrong?
public IEnumerable<ActorDto> SearchMembersInLists(ListMembersQuery query)
{
IEnumerable<ActorDto> result = null;
var sql = #"select DISTINCT t.ActorId,
a.Id, a.TypeId, a.Name, a.Identifier
FROM [ActorTag] t
INNER JOIN [Actor] a ON t.ActorId = a.Id
where t.Name IN #tags
";
using (var cnx = DbConnectionFactory.GetDefault().GetConnection())
{
cnx.Open();
var query_result = cnx.QueryMultiple(sql, new { query.Tags});
result = query_result.Read<ActorDto>();
}
return result;
}
the original code is this, i just tried to simplify as I could
public IEnumerable<ActorDto> SearchMembersInLists(ListMembersQuery query)
{
IEnumerable<ActorDto> result = null;
var sql = #"
SELECT DISTINCT a.Id, a.TypeId, a.Name, a.Identifier,a.Description, a.Email, a.PictureUrl, a.DisplayName --Actor
FROM [RoleMember] lm
INNER JOIN [Actor] a ON lm.ActorId = a.Id
WHERE {tag_filter} {lists_filter}
ORDER BY a.DisplayName DESC OFFSET #pageIndex ROWS FETCH NEXT #pageSize ROWS ONLY
";
bool has_tags = true;
bool has_lists = true;
if (query.Tags != null && query.Tags.Any())
{
sql = sql.Replace("{tag_filter}", "a.Id IN (SELECT t.ActorId FROM [ActorTag] t WHERE t.Name IN #tags)");
has_tags = true;
}
else
{
sql = sql.Replace("{tag_filter}", "");
has_tags = false;
}
if (query.Lists != null && query.Lists.Any())
{
if (has_tags)
{
sql = sql.Replace("{lists_filter}", "AND lm.RoleId IN #lists");
}
else
{
sql = sql.Replace("{lists_filter}", "lm.RoleId IN #lists");
}
has_lists = true;
}
else
{
sql = sql.Replace("{lists_filter}", "");
has_lists = false;
}
if (!has_tags && !has_lists){
sql = sql.Replace("WHERE", "");
}
var values = new
{
lists = query.Lists,
tags = query.Tags,
pageIndex = query.PageIndex * query.PageSizeOrDefault,
pageSize = query.PageSizeOrDefault
};
using (var cnx = DbConnectionFactory.GetDefault().GetConnection())
{
cnx.Open();
result = cnx.Query<ActorDto>(sql, values);
}
return result;
}
There is nothing wrong in the code shown, assuming you're using the latest version of dapper. A similar example is shown below (that can be run in a console exe etc). Please check your data is what you expect.
Note; the query code can actually be significantly simplified, but I wanted to keep it as similar to your example as possible. The simple alternative is here:
public static IEnumerable<ActorDto> SearchMembersInLists(ListMembersQuery query)
{
using (var cnx = GetConnection())
{
return cnx.Query<ActorDto>(
#"select Id, Name from FooActors where Name IN #Tags", new { query.Tags });
}
}
The full program with the more complex query layout is shown below. The output is:
2: Barney
4: Betty
using Dapper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
class Program
{
static void Main()
{
// reset and populate
using (var conn = GetConnection())
{
conn.Open();
try { conn.Execute(#"drop table FooActors;"); } catch { }
conn.Execute(#"create table FooActors (
Id int not null primary key identity(1,1),
Name nvarchar(50) not null);");
conn.Execute(#"insert FooActors(Name) values(#Name);", new[]
{
new { Name = "Fred" },
new { Name = "Barney" },
new { Name = "Wilma" },
new { Name = "Betty" },
});
}
// run a demo query
var tags = new[] { "Barney", "Betty" };
var query = new ListMembersQuery { Tags = tags };
var actors = SearchMembersInLists(query);
foreach(var actor in actors)
{
Console.WriteLine("{0}: {1}", actor.Id, actor.Name);
}
}
public static IDbConnection GetConnection()
{
return new SqlConnection(
#"Initial Catalog=master;Data Source=.;Integrated Security=SSPI;");
}
public class ActorDto
{
public int Id { get; set; }
public string Name { get; set; }
}
public class ListMembersQuery
{
public string[] Tags { get; set; }
}
public static IEnumerable<ActorDto> SearchMembersInLists(ListMembersQuery query)
{
IEnumerable<ActorDto> result = null;
const string sql = #"select Id, Name from FooActors where Name IN #Tags";
using (var cnx = GetConnection())
{
cnx.Open();
var query_result = cnx.QueryMultiple(sql, new { query.Tags });
result = query_result.Read<ActorDto>();
}
return result;
}
}

Display data on grid from multiple tables in c# while using join in stored procedure

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.

Categories