【问题标题】:difficulty inserting a name to an inserted object of a checkedlistbox难以将名称插入到选中列表框的插入对象中
【发布时间】:2010-11-23 04:14:07
【问题描述】:

我是 C# 的新手,我正在尝试将一个对象插入到 CheckedListBox, 所以这个插入的项目将在选中列表中有一个标题(我的对象包含一个字符串字段,我想在 CheckedListBox 中显示它)。 例如这是我的课:

 public class InfoLayer
{
    private string LayerName;
    private List<GeoInfo> GeoInfos;
    public InfoLayer()
    {
        LayerName = "New Empty Layer";
        GeoInfos = new List<GeoInfo>();
    }
    public InfoLayer(string LayerName)
    {
        this.LayerName = LayerName;
        GeoInfos = new List<GeoInfo>();
    }
    public InfoLayer(string LayerName,List<GeoInfo> GeoInfosToClone):this(LayerName)
    {
        foreach (GeoInfo item in GeoInfosToClone)
        { 
             GeoInfos.Add((GeoInfo)((ICloneable)item).Clone());
        }
    }
    public GeoInfo SearchElement(long id)
    {
        foreach (GeoInfo info in GeoInfos) // foreach loop running on the list 
        {
            if (info.INFOID == id) 
                return info; // return the item if we found it
        }
        return null;
    }

    public GeoInfo SearchElement(string name)
    {
        foreach (GeoInfo info in GeoInfos)
        {
            if (info.INFONAME.CompareTo(name)==0)
                return info;
        }
        return null;
    }

    public override string ToString()
    {
        string toReturn = "";
        for (int i = 0; i < GeoInfos.Count; i++) // for loop running on the list 
        {
            toReturn += String.Format("{0}\n",GeoInfos[i].ToString()); // piping another geoinfo 
        }
        return toReturn;
    }

    public string LAYERNAME{get{return LayerName;}}

我的班级还包含一个 tostring 覆盖器(不是我想要显示的)

提前感谢您的帮助。

【问题讨论】:

  • 你能给我们看一些你尝试和上课的代码吗?
  • 您希望您的新行如何显示在 CheckedListBox 中?
  • 层的名称我可以为它创建一个道具...我的课程包含一个字符串名称字段我将把道具添加到问题中
  • 您的 ToString() 方法将返回一个多行字符串。这是你的意图吗?
  • 确实是其他用途(tostring)

标签: c# winforms checkedlistbox


【解决方案1】:

在你的类中重写 ToString(),该类是对象的实例。

编辑:

您不想显示ToString() 的内容。你想显示LayerName,不是吗?也许您应该改为使用 Databinding 显示值。然后您可以将DisplayMember 设置为您的新LAYERNAME 属性。

【讨论】:

  • +1 我误解了这个问题,你的回答很清楚。 =)
  • @Nadav:如果 ToString() 不起作用,那么当您添加对象时,CheckedListBox 中会显示什么文本?
  • 在您开始在 CheckedListBox 上使用数据绑定之前,请阅读以下内容:stackoverflow.com/questions/1346686/…
【解决方案2】:

我相信这就是你想要达到的目标:

checkedListBox1.Items.Add(yourObject.stringField);

【讨论】:

  • 不,我希望列表包含对象和复选框以将对象的 txt 字段作为名称。如果是这样的话,那就太容易了
【解决方案3】:

((MyObjectType)checkedListBox1.Items(index)).Name = "whatever"

您必须知道要更改的对象的索引。

您只需覆盖类中的 ToString 方法,使其返回此 Name 属性值。

public overrides string ToString() {
    return Name;
}

它会在添加到您的CheckedListbox 时显示其名称。

【讨论】:

  • 我不想更改对象内的字段
  • 我希望选中的列表框在插入的项目旁边有我要放置的项目的名称
  • 如果我可以这样说,在您的问题中提及这一点会更清楚。 =) 编辑了我的答案。
  • 我的班级已经有一个 tostring 覆盖功能,但它不起作用
猜你喜欢
  • 2023-02-04
  • 1970-01-01
  • 1970-01-01
  • 2020-11-08
  • 2013-07-02
  • 2017-07-24
  • 2023-03-08
  • 2018-12-01
  • 2020-11-22
相关资源
最近更新 更多