Freelancer
Freelancer

Reputation: 9074

Not able to bind grid in WPF

I am new with WPF.

I am attempting to bind datagrid in WPF.

My Code:

con = new SqlConnection(conClass.conSTR);
            try
            {
                con.Open();
                cmd = new SqlCommand("select * from login",con);
                da = new SqlDataAdapter(cmd);
                DataTable dt=new DataTable("login"); //DataSet ds = new DataSet(); 
                da.Fill(dt);
                gv.ItemsSource = dt.DefaultView;

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

XAML:

<Window x:Class="WpfTestApp.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Window1" Height="428" Width="503" Loaded="Window_Loaded" xmlns:telerik="http://schemas.telerik.com/2008/xaml/presentation">
    <Grid>
        <TextBlock Margin="10" Text="This is a text block" Foreground="Red" TextTrimming="CharacterEllipsis" FontStretch="Normal" FontWeight="Bold"></TextBlock>
        <TextBox Height="23" HorizontalAlignment="Left" Margin="10,29,0,0" Name="txtLoginID" VerticalAlignment="Top" Width="120" />
        <PasswordBox Name="txtPassword" PasswordChar="*" Margin="146,28,221,337"></PasswordBox>
        <Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="100,83,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click"  />
        <DataGrid AutoGenerateColumns="False" Height="247" HorizontalAlignment="Left" Margin="37,130,0,0" Name="gv" VerticalAlignment="Top" Width="303" />
    </Grid>
</Window>

There is no error in this code.

But still my grid is not bound to the table.

It just shows me horizontal lines.

Screenshot:

enter image description here

I don't understand why i am facing this problem.

Please guide me.

EDIT:

Grid after <DataGrid AutoGenerateColumns="True">

enter image description here

Upvotes: 0

Views: 95

Answers (3)

Jason Li
Jason Li

Reputation: 1585

change <DataGrid AutoGenerateColumns="False"> to

<DataGrid AutoGenerateColumns="True">

Add RowHeight="25" to DataGrid

Upvotes: 1

Madurika Welivita
Madurika Welivita

Reputation: 900

try changing as follows:

<DataGrid AutoGenerateColumns="True" DataContext="{Binding}"> 

Upvotes: 2

Rune Grimstad
Rune Grimstad

Reputation: 36320

Try to change your Xaml and set AutoGenerateColumns="True".

This allows the grid to create columns for your data. If you don't set it to true, you must add Column definitions for the columns you want to show.

Upvotes: 1

Related Questions