Hello
I'm fairly new to c# coming from an access background, what I am trying to do is populate a combo box from a forms load event. Is there a way I can hide the Auto number (pTypeID) and display the text description field (pType) while keeping the pTypeID as the cboPTypes.SelectedItem?
Thanks in advance.
Roy.
cboPTypes.Items.Clear();
//Create Connection
OleDbConnection conn = new OleDbConnection(@"provider=Microsoft.Jet.OLEDB.4.0; data source=c:\dBPhones.mdb");
try
{
//Open Connection
conn.Open();
OleDbCommand cmd = new OleDbCommand("SELECT p.pTypeID, p.pType FROM tblPhoneTypes AS p ORDER BY p.pType;", conn);
OleDbDataReader myReader;
myReader = cmd.ExecuteReader();
while (myReader.Read())
{
int phType = (int)myReader["pTypeID"];
string phDesc = (string)myReader["pType"];
cboPTypes.Items.Add(phType + ", " + phDesc);
}
}
catch
{
}
finally
{
if (conn != null)
conn.Close();
}
AlanPosted Mar 17, 2008, 3:51 PM
Well, the SelectedItem property returns an object rather than the displayed string so you can do this in a roundabout way by creating a custom class to encapsulate both the id and the text description. For example:
public class MyClass
{
int id;
public int Id
{
get{return id;}
}
string text;
public string Text
{
get{return text;}
}
public MyClass(int id, string text)
{
this.id = id;
this.text = text;
}
public override string ToString()
{
return text;
}
public static bool operator == (MyClass mc1, MyClass mc2)
{
return mc1.id == mc2.id;
}
public static bool operator != (MyClass mc1, MyClass mc2)
{
return mc1.id != mc2.id;
}
public override bool Equals(object obj)
{
return this == (MyClass)obj;
}
}
You can then add objects to the combobox with code like this:
while (myReader.Read())
{
int phType = (int)myReader["pTypeID"];
string phDesc = (string)myReader["pType"];
cboPTypes.Items.Add(new MyClass(phType, phDesc));
}
As the ToString() method has been defined to just show the text description, that's all that will appear in the combobox. The Equals() method has been overridden to enable objects to be identified within the Items collection when you set the SelectedItem property.
You can easily recover the id of the currently selected object and display it in a textbox with code like this:
if (cboPTypes.SelectedItem != null)
{
textBox1.Text = ((MyClass)cboPTypes.SelectedItem).Id.ToString();
}