0

我一直在为这个问题而烦恼,我的 ToString 是一个接一个地重复,而不是掉到下一行。

如图所示,第二个事件名称应该在下面的行中。

问题

//ToString method in Event Class
public override string ToString()
    {
        return "\nEvent name : " + m_evName + "\n Date :" + m_evDate + "\n";
    }

//print method in class
 public String PrintEvents()
    {
        StringBuilder retev = new StringBuilder("");

        foreach (Event e in m_events)
        {
            retev.Append(e.ToString() + "\n");
        }
        return retev.ToString();
    }



//Foreach that displays the text
private void cboListEv_SelectedIndexChanged(object sender, EventArgs e)
    {
        String SelectedVenue = cboListEv.Text;

        List<Venue> found = plan.selectVen(SelectedVenue);

        lstEvents.Items.Clear();

        foreach (Venue v in found)
        {
                lstEvents.Items.Add(v.PrintEvents());
        }
    }
4

4 回答 4

3

无法ListBox使用标准为每个项目打印多个文本行ListBox。尝试使用 aTextBox代替, withMultiline = true和只读模式。它将达到类似的效果。

除此之外,您还需要使用支持多行数据的自定义项模板来绘制自己的自定义 ListBox 控件。

于 2012-04-12T20:34:19.783 回答
2

ListBox项目不支持多行字符串。但是,您可以制作ListBox's DrawMode OwnerDrawVariable,然后将以下内容连接到它的MeasureItemDrawItem事件:

    internal int CountOccurrences(string haystack, string needle) {
        int n = 0, pos = 0;
        while((pos = haystack.IndexOf(needle, pos)) != -1) {
            n++;
            pos += needle.Length;
        }
        return n;
    }

    void ListBox1MeasureItem(object sender, MeasureItemEventArgs e)
    {
        e.ItemHeight = (int)((CountOccurrences(((ListBox)sender).Items[e.Index].ToString(), "\n") + 1) * ((ListBox)sender).Font.GetHeight() + 2);
    }

    void ListBox1DrawItem(object sender, DrawItemEventArgs e)
    {
        string text = ((ListBox)sender).Items[e.Index].ToString();
        e.DrawBackground();
        using(Brush b = new SolidBrush(e.ForeColor)) e.Graphics.DrawString(text, e.Font, b, new RectangleF(e.Bounds.Left, e.Bounds.Top, e.Bounds.Width, e.Bounds.Height));
        e.DrawFocusRectangle();
    }

-- 最终会是这样的:

于 2012-04-12T20:52:18.790 回答
1

如果您为该PrintEvents()方法提供的项目集合,ListBox您可以让它为每个找到的事件添加一个项目。像这样的东西:

//print method in class
public String PrintEvents(ObjectCollection items)
{
    foreach (Event e in m_events)
        items.Add(e.ToString());
}

//Foreach that displays the text
private void cboListEv_SelectedIndexChanged(object sender, EventArgs e)
{
    String SelectedVenue = cboListEv.Text;

    List<Venue> found = plan.selectVen(SelectedVenue);

    lstEvents.Items.Clear();

    foreach (Venue v in found)
       v.PrintEvents(lstEvents.Items);
}
于 2012-04-12T20:43:21.210 回答
1

向类中添加一个Events属性(Venue如果还没有的话)

public List<Event> Events
{
    get { return m_events; }
}

然后像这样添加项目

foreach (Venue v in found) {
    foreach (Event e in v.Events) {
        lstEvents.Items.Add(e);
    }
}
于 2012-04-12T20:51:33.610 回答