Re: databind array to combox
You cannot bind to fields, i.e. public member variables. You can only use properties as DisplayMember and ValueMember. You need to make those variables private and declare a public property for each one, or at least for the ones you want to use as a DisplayMember or ValueMember. It is the .NET convention to declare variables privately and expose them via public properties in almost all cases anyway. For example:
Code:
private string _name;
public string Name
{
get
{
return this._name;
}
set
{
this._name = value;
}
}
You can even use the 'prop' code snippet to create the skeleton code. Just type "prop" and then hit the Tab key twice.
Once you've declared the properties you can then assign a string containing their names to a DisplayMember or ValueMember:
Code:
myComboBox.DisplayMember = "Name";
myComboBox.ValueMember = "Address";
myComboBox.DataSource = myArray;
Re: databind array to combox
still getting the below error message at the line cbCategory.ValueMember= "categoryId";
"Could not bind to the new display member.Parameter name: newDisplayMember"
even though I have a categoryId property set up
public UInt32 categoryId
{
get
{
return _categoryId;
}
set
{
_categoryId = value;
}
}
_categoryId is private
is the problem not occuring becuase this is an array of objects
and when i set cbCategory.ValueMember= "categoryId"; it doesn't know what categoryId is?
any idea how I resolve this?
Re: databind array to combox
Maybe I am missing the point here, since I never used the Binding features before. But, I think you can just override the ToString() method in your class like this:
Code:
public class testObject
{
public string name;
public string title;
public string address;
public override string ToString(){
return name;
}
}
and if you next just set the DataSource property to the array it works as far as I know:
Code:
comboBox1.DataSource = arr;
Next you can just access your address like this:
Code:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
testObject o = (testObject)comboBox1.SelectedItem;
MessageBox.Show(o.address);
}
But please either way don't use public variables. It's a very very very bad practice.
The following is a lot cleaner:
Code:
public class TestObject
{
string strName;
string strTitle;
string strAddress;
public TestObject()
{
}
public TestObject(string name, string title, string address) : this()
{
strName = name;
strTitle = title;
strAddress = address;
}
public string Name
{
get { return strName; }
set { strName = value; }
}
public string Title
{
get { return strTitle; }
set { strTitle = value; }
}
public string Address
{
get { return strAddress; }
set { strAddress = value; }
}
public override string ToString()
{
return strName;
}
}