Reputation: 4297
I have a UserControl with a ComboBox inside. I need to populate ComboBox items using a List property but I get the error below in designer:
constructor on type 'system.string' not found
and Here is my code:
public List<string> comboItems
{
get
{
List<string> n = new List<string>();
foreach (var i in comboBox1.Items)
n.Add(i.ToString());
return n;
}
set
{
if (comboItems == null)
comboItems = new List<string>();
foreach (var i in value)
comboBox1.Items.Add(i);
}
}
Upvotes: 1
Views: 1113
Reputation: 125197
In general it's not a good idea to expose items of the ComboBox
as a string[]
or as a List<string>
because users may set ComboItems[0] = "something"
but it will not change the first element of the combo box items.
But if you are looking for a solution to get rid of the error message which you receive in designer, instead of a List<string>
use a string[]
and change your code to:
public string[] ComboItems {
get {
return comboBox1.Items.Cast<object>()
.Select(x => x.ToString()).ToArray();
}
set {
comboBox1.Items.Clear();
comboBox1.Items.AddRange(value);
}
}
Note
This is the correct way of exposing Items
property of a ComboBox
in a UserControl
:
[Editor("System.Windows.Forms.Design.ListControlStringCollectionEditor, " +
"System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a",
typeof(UITypeEditor))]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public ComboBox.ObjectCollection ComboItems {
get { return comboBox1.Items; }
}
Upvotes: 1
Reputation: 2280
You can use ObjectCollection
for your property and asign it directly to your combobox. This way you are allowed to use the design editor.
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public ObjectCollection ComboItems
{
get
{
return comboBox1.Items;
}
set
{
comboBox1.Items.Clear();
foreach (var i in value)
comboBox1.Items.Add(i);
}
}
Upvotes: 1