How do I Fill a Listbox with a List using a datatable as the source
I have a Datatable that contains a column that I want to use for a List. To test my employeeList out I added a ListBox and then in code I added lstEmployees.ItemsSource = employeeList(cboStore.Text); I know that this is not a "best practice" for a WPF application but I am new to XAML, WPF and C# (coming from VB.Net Winforms) so I am focusing on getting things working first, which I can, then, refactor later (yes I will!).
I am filling my list with the code below, which gets me the correct field becuase I can see the correct values in the debugger. However in the list box I am seeing this ManpowerManager.MainWindow+Employee. as the listed items. What needs to be done to see the LoginId values?
private static List<Employee> employeeList(string store)
{
List<Employee> employeeList= default(List<Employee&开发者_StackOverflow社区gt;);
employeeList = new List<Employee>();
using (DataTable dt = Logins.getDataset(store, "Manpower_SelectLogins"))
{
foreach (DataRow dr in dt.Rows)
{
employeeList.Add(new Employee(dr["LoginId"].ToString()));
}
}
return employeeList;
}
At this point I am not binding it because the ListBox is just a test.
Since you're not binding yet, you would need to set the DisplayMemberPath of the ListBox to the value in the Employee class you wish to see. Right now, it's seeing an ItemSource of object Employee and it doesn't know which member of Employee should be displayed, so it displays the default ToString of the Employee object.
Once you're binding, then you can use a ListBoxItem template and bind to the fields in the Employee object.
EDIT FOR EXAMPLE
If your Employee class looks like this:
public class Employee
{
public string LoginId { get; set;}
}
Then you would set lstEmployees.DisplayMemberPath = "LoginId". You can set this int the ListBox XAML or the code-behind.
private void Form1_Load(object sender, EventArgs e)
{
BJobProviderJob bJPJ=new BJobProviderJob();
DataTable dt;
dt = bJPJ.getAllProviderJobDetails_2(1);
List<myObject> ls = default( List<myObject>);
ls = new List<myObject>();
foreach (DataRow row in dt.Rows)
{
ls.Add(new myObject(Convert.ToInt32(row["JJP_Id"]),row["Job_Name"].ToString()));
}
listBox1.MultiColumn = true;
listBox1.DataSource = ls;
listBox1.DisplayMember = "JPJob";
listBox1.ValueMember = "JPJID";
}
after setting the ItemsSource you should also do
lstEmployees.DisplayMemberPath = "Field of Employee you want to see in the ListBox";
精彩评论