【问题标题】:Add text to string in CheckedListBox if checked?如果选中,将文本添加到 CheckedListBox 中的字符串?
【发布时间】:2013-03-21 22:06:34
【问题描述】:

我正在开发一个简单的待办事项列表程序,用户可以在文本框中键入任何内容,按下按钮,然后将文本作为项目添加到 CheckedListBox。现在,如果选中,我想在每个项目之前添加文本“完成”,然后如果用户取消选中,则删除文本。

代码:

 Private Sub MyCbList_ItemCheck(ByVal sender As System.Object, ByVal e As System.Windows.Forms.ItemCheckEventArgs) Handles MyCbList.ItemCheck
    If MyCbList.Items.Item(MyCbList.SelectedIndex) = True Then
        MyCbList.Items.Item(MyCbList.SelectedIndex) = "Done: " + MyCbList.Items.Item(MyCbList.SelectedIndex)
    Else
        MyCbList.Items.Item(MyCbList.SelectedIndex) = MyCbList.Items.Item(MyCbList.SelectedIndex).Replace("Done: ", "")
    End If
End Sub

我似乎无法让它工作。我以前从未处理过 CheckedListBoxes。

【问题讨论】:

    标签: vb.net string checked checkedlistbox


    【解决方案1】:

    非常接近!目前,您的代码正在查看当前突出显示(未选中)项目的 text = "True"。

    相反,我们需要检查传递给方法的 ItemCheckedEventArgs 参数:

    Private Sub MyCbList_ItemCheck(ByVal sender As System.Object, ByVal e As System.Windows.Forms.ItemCheckEventArgs) Handles MyCbList.ItemCheck
        If e.NewValue = CheckState.Checked Then
            MyCbList.Items.Item(e.Index) = "Done: " + MyCbList.Items.Item(MyCbList.SelectedIndex)
        Else
            MyCbList.Items.Item(e.Index) = MyCbList.Items.Item(MyCbList.SelectedIndex).Replace("Done: ", "")
        End If
    End Sub
    

    【讨论】:

    • 非常感谢您整理我的代码。仍在使用 vb.net 学习新事物。变量“e”到底是什么?
    • .Net 中的每个表单控件事件方法都传入两个参数:“Sender”是引发事件的对象。例如如果您的表单上有 1000 个按钮,“发件人”是实际单击的按钮,因此您不必尝试猜测单击了哪个按钮。 “e”是关于事件的信息。例如,Button.MouseMove 将有一个“e”参数,其中包含鼠标的 X 和 Y 位置。不同的事件有不同的“e”参数,包含有趣的信息。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 2021-06-09
    • 2019-12-17
    • 2015-10-06
    • 2011-08-30
    • 2017-10-28
    • 2014-09-25
    相关资源
    最近更新 更多