|
-
May 26th, 2011, 11:28 AM
#4
Re: Dynamic Object Names
Okay...
Code:
string[] columnNames = new string[] { "one", "two", "three" };
foreach (string colName in columnNames)
{
this.listView1.Columns.Add(colName, 200);
}
That code works perfectly fine... the reason is that listview1.Columns.Add() has an overload that will accept (string, width) and create a new column using that information for you.
You can still do it this way if it is more to your liking...
Code:
string[] columnNames = new string[] { "one", "two", "three" };
for (int colIndex = 0; colIndex < columnNames.Length; colIndex++)
{
ColumnHeader newHeader = new ColumnHeader();
newHeader.Text = columnNames[colIndex];
newHeader.Width = 200;
this.listView1.Columns.Add(newHeader);
}
The problem with using the same variable name twice, is the compiler can't know what you want, do you want a string, or a ColumnHeader called myObject? Once it is initialized as a string, and the compiler sees you try to initialize it again as a ColumnHeader, it attempts to convert it, which fails.
I hope this helps out
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|