Display two or more displaymembers in binded listbox - c#

After joining two tables, i want to display the name and the first_name of user:
string name_p = list_profiles.Text;
int id_profile;
var profile = SundicappEntities.Instance.users_profiles.First(u => u.name_p== name_p);
id_profile = profile.id_profile;
var q =
from user in SundicappEntities.Instance.users
join map in SundicappEntities.Instance.user_profile_map on user.id_user equals map.id_user
where map.id_profile==id_profile
select new
{
user.name_user,
user.f_name_user
};
usersBindingSource1.DataSource = q.ToList();
listBox_map.DataSource = usersBindingSource1;
listBox_map.DisplayMember = "name_user"+" " + "f_name_user";
It returns the correct data, but it display it like this:
{name_user=xxxx.f_name_user=yyyy}
My problem is how to display many displaymembers in listbox!
Thank you to help me.

Create a custom property in your class object that returns you the correct string.
public string ListBoxItemDisplayText
{
get
{
return name_user + " " + f_name_user ;
}
}
You can create this property in the linq new construct as well
select new
{
ListBoxItemDisplayText = user.name_user + " " + user.f_name_user
};
Bind this property to the DisplayMember property.
listBox_map.DisplayMember = "ListBoxItemDisplayText";

Related

SQL combine rows to be able to filter

I want to combine some rows, so I can filter the customers properly.
SELECT
StammIndex
, sPropSet
, bProp01
FROM [Properties] as properties
RIGHT JOIN [Kunden] as kunden
ON Kunden.StammIndex = properties.KundenIndex
"StammIndex" is the customers ID,
"sPropSet" is the property and
"bProp01" tells you if the property is checked (1) or not checked (0)
The problem is, that customers that have checked the property at least once are saved in the Database.
That means, that the customer IDs will be saved multiple times.
Now I want to get all customers, that didn't check the "Serienbrief" property.
SELECT
StammIndex
, sPropSet
, bProp01
FROM [Properties] as properties
RIGHT JOIN [Kunden] as kunden
ON Kunden.StammIndex = properties.KundenIndex
WHERE NOT (sPropSet = 'Serienbrief' AND bProp01 = 1) OR sPropSet IS NULL
Here you can see that customer '10001' is still there, because he got two properties. I want customer '10001' removed too, because he also got the property "Serienbrief" checked.
First post on stackoverflow, so sorry if I didn't explain my problem properly.
If you got any further questions, please feel free to ask.
EDIT*
My Filter is in C#. The Code behind looks like this
internal class FilterEigenschaften
{
public static List<UndBlock> FilterEigenschaftenListe = new List<UndBlock>();
public List<AdressenListe> Filter(Connection conn)
{
Criteria undBlockCriteria = conn.CreateCriteria();
foreach (UndBlock undBlock in FilterEigenschaften.FilterEigenschaftenListe)
{
Criteria oderBlockCriteria = conn.CreateCriteria();
foreach (OderBlock oderBlock in undBlock.OderBlock)
{
Criteria filterBlockCriteria = conn.CreateCriteria();
foreach (FilterBlock filterBlock in oderBlock.FilterBlock.Where(y => !string.IsNullOrEmpty(y.Wert)))
{
filterBlockCriteria.AddAnd("sPropSet", Operator.Equal, filterBlock.Kriterium);
filterBlockCriteria.AddAnd("bProp" + this.FiterSqlEigenschaftenFelder(conn, filterBlock), Operator.Equal, 1);
if (filterBlock.Operand == "Ist markiert")
{
}
else
{
}
}
oderBlockCriteria.AddOr(filterBlockCriteria);
}
undBlockCriteria.AddAnd(oderBlockCriteria);
}
string cmdText = $"SELECT Distinct(Kunde.StammIndex) " +
$"FROM {conn.Tablenames[4]} AS Kunde " +
$"RIGHT JOIN {conn.Tablenames[12]} AS Properties " +
$"ON Kunde.StammIndex = Properties.KundenIndex " +
$"WHERE {undBlockCriteria}";
return WordSqlAdressen.GetAdressenListe(conn, cmdText);
}
private string FiterSqlEigenschaftenFelder(Connection conn, FilterBlock filterBlock)
{
for (int i = 1; i < 31; i++)
{
using (Command cmd = conn.CreateCommand($"SELECT sProp{i:00} " +
$"FROM {conn.Tablenames[13]} " +
$"WHERE sPropSet = '{filterBlock.Kriterium}'"))
{
using (DataReader dr = cmd.ExecuteReaderEx())
{
while (dr.Read())
{
if (dr.GetString((0)) == filterBlock.Wert)
{
return i.ToString("00");
}
}
}
}
}
return null;
}
}
I can only use one SQL statement to see, if the property is checked or not checked
You just need to move your condition to your join rather than the where clause.
I.e.
SELECT
*
FROM Kuden k
LEFT JOIN Properties p
ON k.StammIndex = p.KudenIndex
AND p.sPropSet = 'Serienbrief'
AND p.bProp01 = 1
WHERE p.KudenIndex IS NULL;

How to cast a List<T> object into Text

I want to know if I can access an item of my List and assign it to a textbox?
public static List<Product> detailsList = new List<Product>();
Product is my class generated by using LINQ to SQL with fields Name,Code,Details i.e my List contains the items(Name,Code,Details). I want to access the value of the item Details from the list and assign it to a textbox . Something like:
txtDetails.Text = detailsList.Details.ToString()
If you want the details of 1 item:
var detailsList = new List<TaskDto>();
// add items
// this if you know the corect index
txtDetails.Text = detailsList[0].Details;
// if you need to query for example for the item with the correct Id
txtDetails.Text = detailsList.FirstOrDefault(p => p.Id == 1).Details;
You can select first or default from the item based on some criteria, like the name.
public static List<Product> detailsList = new List<Product>();
var prod = detailsList.FirstOrDefault(p => p.Name == 'Ana');
if(prod != null) {
txtDetails.Text = prod.Details;
}
For all items:
var joinSymbol = ", ";
txtDetails.Text = string.Join(joinSymbol, detailsList.Select(detail => detail.Details));
For first item if Details:
txtDetails.Text = detailsList.FirstOrDefault()?.Details ?? string.Empty;
use string.Join() function.
txtDetails.Text = string.Join(",", detailsList.Select(e => e.Details)).ToList());

Can't Select Records from a database table with grouping using Linq

I'm trying to Select an SQL table and grouping columns using Linq to SQL, Entities, or Object (I don't really know what.) I'm a bit new to Linq and could use some help. The code structure is straight-forward in my view. When I don't add in the GroupBy method, it works fine. JT_Temp is an entity model by the way. When I run my code below, it goes to the exception:
The entity or complex type 'JT_Temp' cannot be constructed in LINQ to Entities query.
I have tried this and various stackoverflow solutions but they don't seem to solve and apply to my case.
Here is my current code:
//Goal:
//SELECT EnvelopeCode, Branch_COA, AQ_COA, AQ_Branch, SUM(Amount), AQ_PostStatus FROM JT_Temp
//GROUP BY EnvelopeCode, Branch_COA, AQ_COA, AQ_Branch, AQ_PostStatus
//var csvFilteredRecord = Context.JT_Temp.SqlQuery("SELECT * FROM JT_Temp").ToList<JT_Temp>();
// GROUP BY -- No go; Manual SELECT -- No go;
try
{
var csvFilteredRecord = (
from c in Context.JT_Temp
group c by new
{
c.EnvelopeCode,
c.Branch_COA,
c.AQ_COA,
c.AQ_Branch,
c.AQ_PostStatus
} into i
select new JT_Temp
{
EnvelopeCode = i.Key.EnvelopeCode,
Branch_COA = i.Key.Branch_COA,
AQ_COA = i.Key.AQ_COA,
AQ_Branch = i.Key.AQ_Branch,
//TO-DO SUM(Amount),
AQ_PostStatus = i.Key.AQ_PostStatus
}).ToList();
foreach (var Record in csvFilteredRecord)
{
Console.WriteLine(
Record.EnvelopeCode
+ Record.Branch_COA
+ Record.AQ_COA
//+ Record.Amount
+ Record.AQ_PostStatus
);
}
}
catch (Exception e)
{
Console.WriteLine("---------- " + e.Message);
Console.ReadLine();
}
You can't project into JT_Temp. Just use an anonymous object. Also, no reason to make it a list, so I removed the .ToList()
Query syntax:
var csvFilteredRecord = (
from c in Context.JT_Temp
group c by new
{
c.EnvelopeCode,
c.Branch_COA,
c.AQ_COA,
c.AQ_Branch,
c.AQ_PostStatus
} into i
select new
{
EnvelopeCode = i.Key.EnvelopeCode,
Branch_COA = i.Key.Branch_COA,
AQ_COA = i.Key.AQ_COA,
AQ_Branch = i.Key.AQ_Branch,
//TO-DO SUM(Amount),
AQ_PostStatus = i.Key.AQ_PostStatus
});
Method syntax:
var csvFilteredRecord = Context.JT_Temp.GroupBy(k=> new
{
c.EnvelopeCode,
c.Branch_COA,
c.AQ_COA,
c.AQ_Branch,
c.AQ_PostStatus
},
v=>v.Amount,
(k,v)=>new {
k.EnvelopeCode,
k.Branch_COA,
k.AQ_COA,
k.AQ_Branch,
k.AQ_PostStatus
Amount=v.Sum()
});
foreach (var Record in csvFilteredRecord)
{
Console.WriteLine(
Record.EnvelopeCode
+ Record.Branch_COA
+ Record.AQ_COA
+ Record.Amount
+ Record.AQ_PostStatus
);
}

Use Dynamic LINQ Library with join

Following is the UI :
And this is code snippet i am using to fire dynamic where clause :
public void bind()
{
string filter = "";
if (!string.IsNullOrEmpty(txtPart.Text))
{
filter = filter + "masterinv.inv_item_id = " + txtPart.Text;
}
if (!string.IsNullOrEmpty(txtDescription.Text))
{
if (!string.IsNullOrEmpty(filter))
{
filter = filter + " || masterinv.description = " + txtDescription.Text;
}
else
{
filter = filter + "masterinv.description = " + txtDescription.Text;
}
}
if (!string.IsNullOrEmpty(txtVendor.Text))
{
if (!string.IsNullOrEmpty(filter))
{
filter = filter + " || vendor.vendor_name = " + txtVendor.Text;
}
else
{
filter = filter + "vendor.vendor_name = " + txtVendor.Text;
}
}
InventoryDataContext dc = new InventoryDataContext(InventoryDBContext.GetConnectionstring());
var searchResult = (from masterinv in dc.OMS_REF_Master_Inventories
join vendor in dc.OMS_REF_Vendors on masterinv.inv_item_id equals vendor.inv_item_id
Where(filter)
select new OMS_REF_Master_Inventory
{
inv_item_id = masterinv.inv_item_id,
description = masterinv.description,
unit_of_measure = masterinv.unit_of_measure,
lot_id = masterinv.lot_id,
serial_id = masterinv.serial_id,
mfg_id = masterinv.mfg_id,
mfg_item_id = masterinv.mfg_item_id,
item_status_current = masterinv.item_status_current,
cm_unit_cost = masterinv.cm_unit_cost,
sync_dte = masterinv.sync_dte
}).ToList();
searchResult;
}
In the above code filter created on the basis of combination of combo box and text field
selection.
Out of these one filter is :
masterinv.inv_item_id = 'A' || masterinv.description = 'F' || vendor.vendor_name = 'V'
it may vary depend upon the combobox value selection. All cases of Combo box present in BuildQueryFilter Method.
PROBLEM :
I am not able to fire where clause in this join. Where i am going wrong ?
I think you cannot use those % with linq queries.
Instead of % you can use Contains()/StartsWith()/EndsWith()
refer this for more info...
How to do SQL Like % in Linq?
How to do a LIKE query with linq?
Or
Use Sql Methods..
where SqlMethods.Like(c.CustomerName, "%/abc/%")

filtered Query for objectContext Using Linq to SQL

i have tried to search some examples about my approach but all questions was not close enough to what i was trying to achieve .
for the TLDR sake , Question is : how do i make it work as in plain sql query?
using c# - Winforms with SqlCompact4 and Linq to SQL
my scenario involves a form with all the relevant Db table columns as availble filters to query
and then on text change event of each filtertextbox as a filter, the datasource of the gridview updates accordingly
and because i allow filtered search via many of them columns i was trying to avoid use of some extra
lines of code.
so lets say we only concentrate on 4 columns
custID, name, email, cellPhone
each has its corresponding TextBox.
i am trying to make a query as follows :
first i systematically collect all Textbox into a List
var AllFormsSearchFiltersTBXLst = new List<TextBox>();
code that collects all tbx on current form
var AllFormsSearchFiltersTBXLst = [currentFormHere].Controls.OfType<TextBox>();
so now i have all of textboxes as filters regardless if they have any value
then check who has some value in it
forech textbox in this filters textboxes if text length is greater than zero
it means that current filter is active
then.. a second list AllFormsACTIVESearchfiltersTBXLst will contain only active filters
what i was trying to achieve was in same way i didn't have to specify each of textbox objects
i just looped through each of them all as a collection and didn't have to specify each via it's id
now i want to make a filter on a dbContext using only those active filters
so i will not have to ask if current tbxName is email
like
query = db.Where(db=>db.email.Contains(TbxEmail.Text));
and again and again for each of 10 to 15 columns
what i have got so far is nothing that implements what i was heading to.
using (SqlCeConnection ClientsConn = new SqlCeConnection(ConfigurationManager.ConnectionStrings["Conn_DB_RCL_CRM2014"].ConnectionString))
{
System.Data.Linq.Table<ContactsClients> db = null;
// get all column names from context
var x =(System.Reflection.MemberInfo[]) typeof(ContactsClients).GetProperties();
using (DB_RCL_CRM2014Context Context = new DB_RCL_CRM2014Context(ClientsConn))
{
if (!Filtered)
db = Context.ContactsClients;//.Where(client => client.Name.Contains("fler"));
else
{
db = Context.ContactsClients;
// filters Dictionary contains the name of textBox and its value
// I've named TBX as Columns names specially so i could equalize it to the columns names when needed to automate
foreach (KeyValuePair<string,string> CurFltrKVP in FiltersDict)
{
foreach (var memberInfo in x)
{
// couldn't find out how to build the query
}
}
}
BindingSource BS_Clients = new BindingSource();
BS_Clients.DataSource = db;
GV_ClientInfo_Search.DataSource = BS_Clients;
what i normally do when working with plain sql is
foreach textbox take its value and add it into a string as filter
var q = "where " ;
foreach(tbx CurTBX in ALLFILTERTBX)
{
q +=CurTBX.Name +" LIKE '%" + CurTBX.Text + "%'";
// and some checking of last element in list off cores
}
then pass this string as a filter to the main select query ... that simple
how do i make it work as in plain sql query?
I think that you're trying to get the property of db dynamically, like: db.email according to the looped name of your textbox (here 'email'). However, I recommend you to do it some other way. I'd make a switch for each type of the property, like: email, name etc. Something like this:
// Create a list for the results
var results = new List<YourDBResultTypeHere>();
foreach(tbx CurTBX in ALLFILTERTBX)
{
switch(CurTBX.Name) {
case "email":
results.AddRange(db.Where(db => db.email.Contains(tbx.Text)).ToList());
break;
case "name":
results.AddRange(db.Where(db => db.name.Contains(tbx.Text)).ToList());
break;
}
}
try this
void UpdateGridViewData(bool Filtered=false, Dictionary<string,string> FiltersDict = null)
{
using (SqlCeConnection ClientsConn = new SqlCeConnection(ConfigurationManager.ConnectionStrings["Conn_DB_RCL_CRM2014"].ConnectionString))
{
System.Data.Linq.Table<ContactsClients> db = null;
IEnumerable<ContactsClients> IDB = null;
BindingSource BS_Clients = new BindingSource();
System.Reflection.MemberInfo[] AllDbTblClientsColumns = (System.Reflection.MemberInfo[])typeof(ContactsClients).GetProperties();
using (DB_RCL_CRM2014Context Context = new DB_RCL_CRM2014Context(ClientsConn))
{
if (!Filtered)
{
db = Context.ContactsClients;
BS_Clients.DataSource = db;
}
else
{
string fltr = "";
var and = "";
if (FiltersDict.Count > 1) and = "AND";
for (int i = 0; i < FiltersDict.Count; i++)
{
KeyValuePair<string, string> CurFltrKVP = FiltersDict.ElementAt(i);
if (i >= FiltersDict.Count-1) and = "";
for (int j = 0; j < AllDbTblClientsColumns.Length; j++)
{
if (AllDbTblClientsColumns[j].Name.Equals(CurFltrKVP.Key))
{
fltr += string.Format("{0} Like '%{1}%' {2} ", AllDbTblClientsColumns[j].Name, CurFltrKVP.Value, and);
}
}
}
try
{
IDB = Context.ExecuteQuery<ContactsClients>(
"SELECT * " +
"FROM ContactsCosmeticsClients " +
"WHERE " + fltr
);
BS_Clients.DataSource = IDB;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
GV_ClientInfo_Search.DataSource = BS_Clients;
}
}
}

Categories

Resources