문제

I want to have a number of objects that can be added to a checkedListBox in C# and have the objects be able to generate their own strings that are displayed in the list. I found an example of what I want to do in visual basic.

However, I can't figure out how to do it in c#. I've tried to implement my own class :

public class Device  {
    String s;

    public Device() {
        s = new String("test".ToCharArray());

    }

    public String toString() {
        return s;
    }
}

But when I run it, it displays "WindowsFormsApplication2.Device" in the list, not test..

Any suggestions would be appreciated.

Thanks, Reza

p.s. would it be possible to display text and a progress bar for each entry in a checklistbox?

도움이 되었습니까?

해결책

You are not correctly overriding the Object.ToString() virtual method:

  1. The method-name is spelled incorrectly (C# is case-sensitive).
  2. The override modifier on the method is missing; this is required when over-riding a virtual method.

Do it this way:

public override string ToString()
{
    return s;
}

다른 팁

make your toString method like this:

public override string ToString(){
    return s;
}

the_ajp pointed correctly that the real problem is the camelCase toString when it should be PascalCase ToString.

public override String ToString() {
    return s;
}

Also, don't look at Java examples when coding C#, the s = new String("test".ToCharArray()); should be just s = "test";.

You already have an answer, but here's a trick I like to use. The thing I don't like about using ToString() method on your model is that it mixes bussiness and view logic.

Instead, I create a wrapper class (Adapter design pattern), which keeps a reference to the model object and provides it own ToString method. You can combine this with anonymous functions to specify how exactly the displayed string should be obtained (you may want to display slightly different strings in different list boxes).

The wrapper class could look like this:

class ListBoxWrapper<T>
{
    private T obj;
    private Func<T, string> stringFunction;

    public ListBoxWrapper(T obj, Func<T, string> stringFunction)
    {
        this.obj = obj;
        this.stringFunction = stringFunction;
    }

    public override string ToString()
    {
        return stringFunction(obj);
    }
}

To simply use ToString() of the model, you can still do:

ListBox.Items.Add(new ListBoxWrapper<Device>(device, dev => dev.ToString()));

But you could also do (for example):

ListBox.Items.Add(new ListBoxWrapper<Device>(device, dev => dev.SerialNumber.ToString()));

To make this more useful, you can create your own class derived from ListBox or CheckedListBox, which will wrap your objects automatically. That way, you can also have the string function stored with the ListBox instead of with each individual item.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top