[英]Adding groups and items to ListView in C# windows form
我試圖在Windows窗體中創建一個ListView,其中包含從數據庫中獲取的組和項目。
我的ListView稱為“ lstItems”
首先,ListView是空的,我在程序運行期間用數據填充它。
這是我用來創建組的代碼:
foreach(DataRow r in tasksTbl.Rows)
{
string groupName = "group" + num;
num++;
lstItems.Groups.Add(groupName, r.Field<string>(0));
}
taskTbl表不為空,它創建了一些我目前無法在屏幕上看到的組。
這是我用來為組創建項目和子項目的代碼:
private void CreateItem(DataTable tbl)
{
int taskId = tbl.Rows[0].Field<int>(0);
string taskName = tbl.Rows[0].Field<string>(1);
DateTime startDate = tbl.Rows[0].Field<DateTime>(2);
DateTime endDate = tbl.Rows[0].Field<DateTime>(3);
string dateStr = startDate.ToString() + " - " + endDate.ToString();
ListViewItem item = new ListViewItem(dateStr);
item.Tag = taskId.ToString();
foreach (DataRow r in tbl.Rows)
{
string position = r.Field<string>(5);
string soldier = r.Field<string>(6);
item.SubItems.Add(soldier + " (" + position + ")");
}
foreach(ListViewGroup grp in lstItems.Groups)
if (grp.Header.Equals(taskName))
grp.Items.Add(item);
}
這里的tbl表也不為空,它為每個組創建項目和子項目。
我可以在調試器中看到組中的項目正確。
我的問題是我無法在屏幕上看到組或項目。
我想念什么?
有人可以幫我嗎?
先感謝您!
itzick,
您需要隨時創建組,並將它們分配給添加到ListView控件的項目。 這是一個簡單的示例,該示例加載具有65到76的數字的ListView。這些組基於數字模數5。
創建一個表單,添加一個名為listView1的ListView,添加以下方法,並在表單加載期間調用該方法。 您應該看到一個具有五個組的ListView,每個組中有幾個成員項。
private void LoadListView()
{
// Assume we are in a form, with a ListView control called listView1 on the form
// Create a group label array
var groupLabels = new string[5];
groupLabels[0] = "aaa";
groupLabels[1] = "bbb";
groupLabels[2] = "ccc";
groupLabels[3] = "ddd";
groupLabels[4] = "eee";
for (var i = 65; i < 76; i++)
{
// Find group or create a new group
ListViewGroup lvg = null;
var found = false;
foreach (var grp in listView1.Groups.Cast<ListViewGroup>().Where(grp => grp.ToString() == groupLabels[i % 5]))
{
found = true;
lvg = grp;
break;
}
if (!found)
{
// Group not found, create
lvg = new ListViewGroup(groupLabels[i % 5]);
listView1.Groups.Add(lvg);
}
// Add ListViewItem
listView1.Items.Add(new ListViewItem {Text = i.ToString(CultureInfo.InvariantCulture), Group = lvg});
}
我發現了我的問題。
我需要將列添加到ListView,然后將項目添加到ListView,最后才將項目添加到組。
我做到了,現在可以了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.