You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

点击多按钮无法为ListView同一行不同列添加子项如何解决?

问题核心

你在button2_Click中创建的ListViewItem属于方法局部变量,在停止计时的方法中无法访问到对应行,因此无法追加结束时间和时长数据,按照以下方案修改即可:


步骤1:在窗体类中声明成员变量

在窗体类的所有方法外部新增两个全局引用,用来记录当前正在计时的笔记对象和对应ListView行:

// 窗体类成员变量,放在所有方法外面
private noteInfos currentNote;
private ListViewItem currentRecordingItem;

步骤2:修改开始计时(button2)逻辑

private void button2_Click(object sender, EventArgs e)
{
    // 初始化当前计时的相关对象
    currentNote = new noteInfos();
    currentRecordingItem = new ListViewItem();
    
    // 写入课程名和开始时间
    currentNote.nameofcourse = textBox1.Text;
    currentRecordingItem.Text = currentNote.nameofcourse;
    listView1.Items.Add(currentRecordingItem);

    DateTime startDate = DateTime.Now;
    currentNote.dateofstart = startDate.ToString();
    currentRecordingItem.SubItems.Add(currentNote.dateofstart);
    
    // 避免重复点击,设置按钮状态
    button2.Enabled = false;
    button3.Enabled = true;
}

步骤3:修改停止计时(button3)逻辑

private void button3_Click(object sender, EventArgs e)
{
    // 校验是否已经启动计时
    if (currentNote == null || currentRecordingItem == null)
    {
        MessageBox.Show("请先点击开始按钮启动计时");
        return;
    }
    
    // 写入结束时间
    DateTime endTime = DateTime.Now;
    currentNote.dateofend = endTime.ToString();
    currentRecordingItem.SubItems.Add(currentNote.dateofend);

    // 计算时长
    convertit();
    
    // 重置按钮状态,准备下次记录
    button2.Enabled = true;
    button3.Enabled = false;
    textBox1.Clear();
}

步骤4:修改时长计算方法

public void convertit()
{
    DateTime dt = Convert.ToDateTime(currentNote.dateofstart);
    DateTime d2 = Convert.ToDateTime(currentNote.dateofend);
    TimeSpan totalDuration = d2.Subtract(dt);
    // 格式化时长为时分秒格式,可读性更强
    currentNote.totalsum = totalDuration.ToString(@"hh\:mm\:ss");
    currentRecordingItem.SubItems.Add(currentNote.totalsum);
    
    // 计时完成后清空引用
    currentNote = null;
    currentRecordingItem = null;
}

前置配置提醒

请先确保你的ListView控件的View属性设置为View.Details,并且提前在Columns集合中添加4列,列名可依次设置为「课程名称」「开始时间」「结束时间」「学习时长」,否则子项数据不会显示。


内容的提问来源于stack exchange,提问作者Orçun Onurkan Demirtürk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 04:48:04