1

I wanted to create a ListView with only one column. In every piece of code I've met I see constructions like this:

listView.Columns.Add("Name", -2, HorizontalAlignment.Left);

I wonder why do everyone pass a -2 here? Where does it come from?

I see that only then my result is what I actually expected it to be but why doesn't something like

listView.Columns.Add("Name");

work properly? It creates like 2 columns, one narrow and one without title.

2 Answers 2

4

Width of -2 indicates auto-size. please read this MSDN article: https://msdn.microsoft.com/en-us/library/6fy0dahz.aspx

Sign up to request clarification or add additional context in comments.

1 Comment

I guess that this is what I was looking for. So -2 is like a special value. Are there any others?
2

To expand on George's answer I'll first say : "always consult the docs."

So I'm trying to explain how you could have gotten the answer yourself.

On MSDN the ListView.Columns property returns a ColumnHeaderCollection. Follow the link for the reference to it here : ColumnHeaderCollection. Find the Add method, the definition is this :

public virtual ColumnHeader Add(
    string text,
    int width,
    HorizontalAlignment textAlign
)

That's straight from MSDN and it's exactly what you're looking for :) ... The second parameter is width. Additionally the docs will mentions notes or any more details you might need to know about the method and/or the parameter.

Update : Now I see what you're asking. Sorry about the misunderstanding. Yes, -2 is a special number and details about other numbers are here on the ColumnHeader.Width page :

This property enables you to set the Width of the ColumnHeader. The ColumnHeader can be set to adjust at run time to the column contents or heading. To adjust the width of the longest item in the column, set the Width property to -1. To autosize to the width of the column heading, set the Width property to -2.

Thankfully there are two magical (or special) values to set all in all.

3 Comments

It doesn't mention if there are any other special values like -2. Why isn't it -1 then?
Wasn't it easier to provide a simple enum? I find these numbers a bit confusing...
Yes it is odd to have magic numbers like this. Maybe this is how the ListView control works itself, I mean at the win32 api level. Windows forms is a wrapper over wi 32 api so maybe it always required a -2 or -1 since it was introduced in windows xp or so I think. Anyway even for that digging MSDN pages will give you even historical facts.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.