Click here to Skip to main content
15,892,697 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have problem with adding values in listview from dadabase, have relation with couple tables and here is OK.
In my case i have table with X rows with same values
PrID|koID
1   |5
1   |8
20  |3
6   |80
13  |3
6   |41
ex. for PrID=1 i should get rows for koID 5 and 8 in one cell
but when add i get this, rows from KoID 5 is in one row in listView, koId 8 in other
column1|column2|column3
1      |A      |Item1
1      |B      |Item1
1      |...    |Item1
2      |C      |Item2
3      |B      |Item3
3      |E      |Item3
3      |...    |Item3

should be like this
column1|column2|column3
1      |AB...  |Item1
2      |C      |Item2
3      |BE...  |Item3


What I have tried:

C#
foreach (DataRow row in dt.Rows)
{
string str = row["kon"].ToString()+" "+row["kov"].ToString();

ListViewItem list = new ListViewItem(row["Id"].ToString());
               list.SubItems.Add(str);
               list.SubItems.Add(row["item"].ToString());
               listView1.Items.Add(list);
}
Posted
Updated 16-Mar-20 2:56am

1 solution

You need to group data by PrID. There's few ways to achieve that. One of the simplest is to use Dictionary object.

Take a look at below example:
C#
//sample data 
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[]{new DataColumn("PrID", typeof(int)), new DataColumn("koID", typeof(int))});
dt.Rows.Add(new object[]{1, 5});
dt.Rows.Add(new object[]{1, 8});
dt.Rows.Add(new object[]{20, 3});
dt.Rows.Add(new object[]{6, 80});
dt.Rows.Add(new object[]{13, 3});
dt.Rows.Add(new object[]{6, 41});

//create dictionary object
Dictionary<int, List<int>> d = new Dictionary<int, List<int>>();
//loop through the collection of datatable's rows
foreach(DataRow dr in dt.Rows)
{
	//if key does NOT exist
	if(!d.ContainsKey(dr.Field<int>("PrID")))
		d.Add(dr.Field<int>("PrID"), new List<int>(){dr.Field<int>("koID")});
	else
		d[dr.Field<int>("PrID")].Add(dr.Field<int>("koID"));
}
//add listviewitem and its subitems based on dictionary object
foreach(int k in d.Keys)
{
	ListViewItem lvi = new ListViewItem(k.ToString());
	foreach(int v in d[k])
		lvi.SubItems.Add(v.ToString());
	ListView1.Items.Add(lvi);
}


Other solutions have to be Linq based.
 
Share this answer
 
v2
Comments
Member 11920272 23-Apr-20 3:55am    
Sorry i late

i try with your solution, but this add new coloum in my list, maybe will work in difrent type of list or console app, or i don't know i'm not good with dictonarys, lists...
try and with linq, with static data is OK but from database not work like i want,

so i find solution for my problem with sql query STRING_AGG()

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900