首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Tag problem c#列表框

Tag problem c#列表框
EN

Stack Overflow用户
提问于 2010-03-18 22:14:55
回答 6查看 6.6K关注 0票数 4

您好,我正在尝试使用列表框的标记项。

这是我的代码。

代码语言:javascript
运行
复制
            int number = 0;
            foreach (ListViewItem item in listBox1.Items)
            {
                Tag tag = (Tag) item.Tag;
                saveSlide(showid, tag.photoid, enumber);
                number++;
            }

我的问题是,当我运行程序时,我得到一条错误消息,说我无法将类型字符串转换为system.ListView,但我在程序中的任何地方都没有将项目声明为字符串

这就是我将项目添加到列表框的地方。请帮帮忙。我在死线上,还有很多事情要做

代码语言:javascript
运行
复制
private void buttonAdd_Click(object sender, EventArgs e)
{
    //add selected item into listBox
    DataRowView drv = (DataRowView)listBox1.SelectedItem;
    Tag tag = new Tag();
    string title = drv["title"].ToString();
    ListViewItem item = new ListViewItem(title);
    item.Tag = tag;
    tag.photoid = (int)drv["photoid"];

    listBox1.Items.Add(title);
}
EN

回答 6

Stack Overflow用户

发布于 2010-03-18 22:20:31

Poppy您正在向listBox1.Items添加title

title的类型为string

因此,当您访问它时,使用像这样foreach (string item in listBox1.Items)这样的string类型。

试试看。有帮助吗?

代码语言:javascript
运行
复制
        int number = 0;
        foreach (string item in listBox1.Items)
        {
            Tag tag = (Tag) item.Tag;
            saveSlide(showid, tag.photoid, enumber);
            number++;
        }
票数 2
EN

Stack Overflow用户

发布于 2010-03-18 22:27:11

这是可行的,您需要显示向列表中添加项目的代码:

代码语言:javascript
运行
复制
private class Tag
{
    public override string ToString()
    {
        return "Tag";
    }
}

ListBox listBox = new ListBox();
listBox.Items.Add(new ListViewItem { Tag = new Tag() });
foreach (ListViewItem item in listBox.Items)
{
    Tag tag = (Tag)item.Tag;
    Console.WriteLine(tag);
}

编辑以下更多代码:

您正在将字符串而不是ListViewItem添加到ListBox:

listBox1.Items.Add(title);应为listBox1.Items.Add(item);

票数 2
EN

Stack Overflow用户

发布于 2010-03-18 22:53:17

ListBox.Items是一个ObjectCollection。这意味着您可以选择要放入其中的对象的类型。

当你这样做的时候:

代码语言:javascript
运行
复制
string title = drv["title"].ToString();
listBox1.Items.Add(title);

您要将string对象放入其中,因此需要像这样将它们取出:

代码语言:javascript
运行
复制
foreach (string item in listBox1.Items)

相反,您可能希望您的代码更像这样:

代码语言:javascript
运行
复制
ListViewItem item = new ListViewItem(title);
item.Tag = tag;
tag.photoid = (int)drv["photoid"];
listBox1.Items.Add(item); // The difference is here - add *item* not *title*

然后,您将能够以最初编写的方式使用它:

代码语言:javascript
运行
复制
foreach (ListViewItem item in listBox1.Items)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2470448

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档