简体   繁体   中英

How to bind data to the DataGrid present in the UserControl in WPF

Here I have my UserControl as:

<Border Grid.Column="0" BorderBrush="Black" BorderThickness="2">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="30"/>
            <RowDefinition Height="30"/>
            <RowDefinition Height="30"/>
            <RowDefinition Height="80"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="5*"/>
            <ColumnDefinition Width="5*"/>
        </Grid.ColumnDefinitions>
        <Label Grid.Row="0" Grid.Column="0" Content="Student Name"/>
        <TextBlock Text="{Binding NAME}" Grid.Column="1" Grid.Row="0" HorizontalAlignment="Left" VerticalAlignment="Center"/>
        <Label Grid.Row="1" Grid.Column="0" Content="Roll No"/>
        <TextBlock Text="{Binding ROLL_NO}" Grid.Column="1" Grid.Row="1" HorizontalAlignment="Left" VerticalAlignment="Center"/>
        <Label Grid.Row="2" Grid.Column="0" Content="Class Teacher Name"/>
        <TextBlock Text="{Binding CLASS_TEACHER}" Grid.Column="1" Grid.Row="2" HorizontalAlignment="Left" VerticalAlignment="Center"/>
        <DataGrid Grid.Row="3" Grid.ColumnSpan="2" x:Name="dg_Marks" IsReadOnly="False" ItemsSource="{Binding}" ColumnWidth="*" RowHeaderWidth="0" VerticalAlignment="Top" CanUserAddRows="False" Height="78" AutoGenerateColumns="False">
            <DataGrid.Columns>
                <DataGridTextColumn IsReadOnly="True" Binding="{Binding TEST_NO}" Header="Test No" />
                <DataGridTextColumn IsReadOnly="True" Binding="{Binding ENGLISH}" Header="English" />
                <DataGridTextColumn IsReadOnly="True" Binding="{Binding SOCIAL}" Header="Social" />
                <DataGridTextColumn IsReadOnly="True" Binding="{Binding SCIENCE}" Header="Science" />
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
</Border>

I am using this control in my MainWindow say at different places. Here is my MainWindow.xaml

 <Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="3*"/>
        <ColumnDefinition Width="3*"/>
        <ColumnDefinition Width="3*"/>
    </Grid.ColumnDefinitions>

    <Label Content="Student1:" Grid.Column="0" />
    <local:StudentUserControl x:Name="student1" Margin="10,25,5,0" Width="250" Height="200" VerticalAlignment="Top" />
    <Label Content="Student2:" Grid.Column="1" />
    <local:StudentUserControl Grid.Column="1" x:Name="student2" Margin="10,25,5,0" Width="250" Height="200" VerticalAlignment="Top" />
    <Label Content="Student3:" Grid.Column="2" />
    <local:StudentUserControl Grid.Column="2" x:Name="student3" Margin="10,25,5,0" Width="250" Height="200" VerticalAlignment="Top" />

</Grid>

I am able bind the data from my Database to the labels. But I am unable to bind the data to the DataGrid. Here is my MainWindow.cs

 private void ShowDetails(string strName)
    {
        StudentDetails request = new StudentDetails();

        String retrieveCommand = "Select * from STUDENT_DETAILS where NAME='" + strName + "'";
        DataTable dataTable = MDBConnection.RetreiveTableData(retrieveCommand);

        request.NAME = dataTable.Rows[0]["NAME"].ToString();
        request.ROLL_NO = dataTable.Rows[0]["ROLL_NO"].ToString();
        request.CLASS_TEACHER = dataTable.Rows[0]["CLASS_TEACHER"].ToString();

         retrieveCommand = "Select * from STUDENT_MARKS_DETAILS where NAME='" + strName + "'";
         dataTable = MDBConnection.RetreiveTableData(retrieveCommand);

        // How to bind data to the datagrid of the UserControl

        student1.DataContext = request;
    }

And my StudentDetails class looks like

 public class StudentDetails
{
    public String NAME { get; set; }
    public String ROLL_NO { get; set; }
    public String CLASS_TEACHER { get; set; }
}

So My problem is how can I bind the data in datatable to the dataGrid. Where I have to change please suggest me.

EDIT: I think I have to add something to "StudentDetails"

EDIT 2 As mentioned I added

public List<StudentMarkDetails> StudentMarks { get; set; }

in StudentDetails but getting Null Reference Exception. Even though

public List<StudentMarkDetails> StudentMarks = new List<StudentMarkDetails>();

was added data is not showing in the DataGrid.

I think you are on the right track by setting the DataContext of your UserControls. The problem is that you are setting the DataContext to "request" which limits to what your controls inside the UserControl can bind to.

The DataGrid controls expects a list of something to bind to. When you are using " student1.DataContext = request " + ItemsSource="{Binding}" on your grid , you are essentially binding the grid to a single entity.

What you should do instead is bind the grid to the DataTable itself. Try setting the DataContext like this - student1.DataContext = dataTable.DefaultView ;

If you need to bind both your labels and the DataGrid at the same time, you will have to create a ViewModel that combines all of the data that is needed by your UserControl and use that as a DataContext. ViewModels are essential to WPF. If you haven't studied them I suggest you do. Here is decent introduction - Model-View-ViewModel (MVVM) Explained .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM