Reputation: 174
I am having trouble finding a good solution to this problem and was wondering if anyone would be able to help me with this.
private void frmModifyLeaderID_Load(object sender, EventArgs e)
{
loadEmployees();
}
private void loadEmployees()
{
dsEmployeesemp = new dsEmployees();
cbEmployees.DataSource = emp.getEmployees();
cbEmployees.DisplayMember = "Name";
cbEmployees.ValueMember = "id";
}
private void cbEmployees_SelectedValueChanged(object sender, EventArgs e)
{
if (cbEmployees.SelectedValue != null)
{
tbCurrentTeamLeaderID.Text = cbEmployees.SelectedValue.ToString();
}
}
This code works properly, but now I am running into an issue with a new requirement. When a user selects an item (by employee name) in the ComboBox
(cbEmployees), I now need access to both the "id" column as well as another column in the DataSource emp.getEmployees()
called "LeaderID".
At first I was going to use this solution also found on stackoverflow, but as I am using a DataTable
as the ComboBox
's DataSource
and using that DataTable
's column names as identifiers. I am unsure how to go forward with this.
I was thinking of using an iterative loop to go through the DataTable and create objects with both the "id" and "LeaderID" as the object's properties then store that object in the cbEmployees.ValueMember
, but I can not get this to work.
If anyone knows a better solution it would be very appreciated. Thanks!
Upvotes: 1
Views: 1212
Reputation: 174
I have found a solution to my problem.
After looking at the comments posted to my question, Reza let me know that the items are of type DataRowView
. This made me realize that even though I set the DisplayMember
and ValueMember
of each row, the rest of the data in the DataTable
was still accessible in each row.
With this realization, I changed my cbEmployees_SelectedValueChanged
method to this:
var selectedEmp = (DataRowView)cbEmployees.SelectedItem;
tbCurrentTeamLeaderID.Text = selectedEmp["LeaderID"].ToString();
And with this, it now properly accesses and sets the value taken from the LeaderID
column of the DataTable
.
Thanks for the input!
Upvotes: 1