【问题标题】:I can't add subitems to a ListView using more than one Button我无法使用多个按钮将子项添加到 ListView
【发布时间】:2021-11-13 14:42:00
【问题描述】:

我正在尝试为自己制作一些笔记应用程序。
我可以成功获取课程名称、开始日期、结束日期和工作时间。
问题是当我单击停止按钮时,我无法弄清楚如何将其他数据添加到同一行但添加到不同的列。

private void button2_Click(object sender, EventArgs e)
{
    ListViewItem item = new ListViewItem();
    note.nameofcourse = textBox1.Text;
    item.Text = note.nameofcourse;
    listView1.Items.Add(item);

    DateTime date = DateTime.Now;
    note.dateofstart = date.ToString();
    item.SubItems.Add(note.dateofstart);
}

private void button3_Click(object sender, EventArgs e)
{
    DateTime time_2 = DateTime.Now;
    note.dateofend = time_2.ToString();

    convertit();
}

public void convertit()
{
    DateTime dt = Convert.ToDateTime(note.dateofstart);
    DateTime d2 = Convert.ToDateTime(note.dateofend);
    TimeSpan totalsum = d2.Subtract(dt);
    note.totalsum = totalsum.ToString();
    //item.SubItems.Add(note.totalsum);
}

这也是我的class.cs

class noteInfos
{
    public string nameofcourse;
    public string dateofstart;
    public string dateofend;
    public string totalsum;
}

【问题讨论】:

  • ListView 比例如使用起来更尴尬。数据网格视图;制作一个包含相关列的数据表,将其绑定到 DGV(DGV 上的数据源属性),然后将行添加到表中,它们将出现在网格中
  • 感谢您提供的信息丰富的回答。我对 OOP 的逻辑很陌生。这肯定会帮助我。

标签: c# winforms listview


【解决方案1】:

我以某种方式解决了这个问题。首先,如果您甚至不添加任何内容,您应该创建该行。然后您可以使用最后一段代码编辑这些行。

private void button2_Click(object sender, EventArgs e)
    {
        ListViewItem item = new ListViewItem();
        note.nameofcourse = textBox1.Text;
        item.Text = note.nameofcourse;
        listView1.Items.Add(item);

        DateTime date = DateTime.Now;
        note.dateofstart = date.ToString();
        item.SubItems.Add(note.dateofstart);
        item.SubItems.Add(note.dateofend);
        item.SubItems.Add(note.totalsum);
    }

然后我也添加了一些奇怪的东西。

                int sayi = listView1.Items.Count;
                listView1.Items[sayi -1].SubItems[2].Text = note.dateofend;
                listView1.Items[sayi -1].SubItems[3].Text = note.totalsum;
                note.totalsum = "";
                note.dateofend = "";

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    相关资源
    最近更新 更多