atulya
atulya

Reputation: 539

WPF + ListBox Databinding system.data.DataRowView

I am trying to fill Listbox after fetching data from the database in WPF application.

I have a class that return DataTable

class DataBaseTable
{
    MySqlConnection connection;
    MySqlDataAdapter adapter;
    public DataTable GetTable(String query, String sortBy)
    {
        String connString = "server=localhost;uid=root;pwd=MyNewPass123;database=samprojects;";
        connection = new MySqlConnection(connString);
        adapter = new MySqlDataAdapter(query, connection);
        DataTable dataTable = new DataTable();
        adapter.Fill(dataTable);
        dataTable.DefaultView.Sort = sortBy;          
        return dataTable;
    }
}

And the XAML code

<ListBox Name="listbox1" Width="150" Height="150" SelectionMode="Single" ItemsSource="{Binding}" />

And Main Window Class

public partial class MainWindow : Window
{
    private DataBaseTable dbTable = new DataBaseTable();
    public MainWindow()
    {
        InitializeComponent();

        listbox1.DataContext = dbTable.GetTable("select name from projects", "name");            
    }
}

But my List Box is getting filled with

  System.Data.DataRowView
  System.Data.DataRowView
  System.Data.DataRowView

Not able to get what is getting wrong?

Upvotes: 0

Views: 1629

Answers (2)

Franck
Franck

Reputation: 4440

By default the control will show the .ToString() of the object. since it's a datarowview it shows the assembly name only. what you want is setting the DisplayMemberPath

<ListBox Name="listbox1" Width="150" Height="150" SelectionMode="Single" ItemsSource="{Binding}" DisplayMemberPath="MyColumn"/>

Upvotes: 1

Ric
Ric

Reputation: 13248

Try this:

<ListBox Name="listbox1" Width="150" Height="150" SelectionMode="Single" ItemsSource="{Binding}" />
  <ListBox.ItemTemplate>
    <DataTemplate>
      <TextBlock Text="{Binding name}" />
    </DataTemplate>
  </ListBox.ItemTemplate>
</ListBox>

There is also more information on the subject here:

Data Templates

Upvotes: 1

Related Questions