Ahmad Gulzar
Ahmad Gulzar

Reputation: 363

Listbox Databinding in wpf

I am binding the data coming form database to ListBoxItem's, below is the code:

public void load_users()
{
    RST_DBDataContext conn = new RST_DBDataContext();
    List<TblUser> users = (from s in conn.TblUsers
                                  select s).ToList();
    Login_Names.ItemsSource = users;
}

And in XAML, there is the below code:

<ListBox Name="Login_Names" 
         ItemsSource="{Binding Path=UserName}"
         HorizontalAlignment="Left" 
         Height="337" Margin="10,47,0,0"
         Padding="0,0,0,0" VerticalAlignment="Top" Width="156">

But it does not works, it shows table name, but I need to see the usernames coming from table, there is column called UserName in TblUsers.

Thanks in Advance.

Upvotes: 6

Views: 15231

Answers (2)

Anusha Busetty
Anusha Busetty

Reputation: 81

Since the ItemsSource is set already in code behind, set the DisplayMemberPath to UserName in XAML.

<ListBox Name="Login_Names" 
     DisplayMemberPath="UserName"
     HorizontalAlignment="Left" 
     Height="337" Margin="10,47,0,0"
     Padding="0,0,0,0" VerticalAlignment="Top" Width="156">

Upvotes: 0

santosh singh
santosh singh

Reputation: 28672

try this

Create DataTemplate in resource section and then assign it to listbox

<Grid.Resources>
        <DataTemplate x:Key="userNameTemplate">

                <TextBlock Text="{Binding Path=UserName}"/>

        </DataTemplate>

 <ListBox Name="listBox" ItemsSource="{Binding}"
            ItemTemplate="{StaticResource userNameTemplate}"/>

Upvotes: 8

Related Questions