Search code examples
c#wpfc#-4.0wpf-controlswpfdatagrid

Add Dynamic Button in datagridView Rows Wpf


I am using WPF Application. I need to Create Button Dynamically with some properties and i add the buttons in dataGridView Rows. But Datatable is not Contains The Button DataType Then how to do this Please Someone Help me thanks in advance.

This is My Code:

DataTable NewDataTable = new DataTable();
for (int i = 0; i < Row * level; i++)
{
    Button[] buttonArray = new Button[position];
    string Col1 = "Rows";
    string Col2 = "Levels";
    for (int j = 0; j < position; j++) 
    {                    
        if (j == 1) 
        {
            Col1 = "Rows";
        }
        else if (j == 2)
        {
            Col2 = "Levels";
        }
        else 
        {
            buttonArray[j] = new Button();
            buttonArray[j].Content = "Postion " + j;
            buttonArray[j].ToolTip = "Postion " + j;

        }                    
    }
    NewDataTable.Rows.Add(Col1, Col2, buttonArray[j]);
}

Code Behind

Dgrid.ItemsSource = NewDataGrid.DefaultView();

Solution

  • It sounds like you haven't yet met the DataGridTemplateColumn Class. Let me introduce to you the column that can contain any controls in it... from the linked page:

    Represents a DataGrid column that hosts template-specified content in its cells.

    An example, again from the linked page:

    <Grid>
        <Grid.Resources>
            <!--DataTemplate for Published Date column defined in Grid.Resources.  PublishDate is a property on the ItemsSource of type DateTime -->
            <DataTemplate x:Key="DateTemplate" >
                <StackPanel Width="20" Height="30">
                    <Border Background="LightBlue" BorderBrush="Black" BorderThickness="1">
                        <TextBlock Text="{Binding PublishDate, StringFormat={}{0:MMM}}" FontSize="8" HorizontalAlignment="Center" />
                    </Border>
                    <Border Background="White" BorderBrush="Black" BorderThickness="1">
                        <TextBlock Text="{Binding PublishDate, StringFormat={}{0:yyyy}}" FontSize="8" FontWeight="Bold" HorizontalAlignment="Center" />
                    </Border>
                </StackPanel>
            </DataTemplate>
            <!--DataTemplate for the Published Date column when in edit mode. -->
            <DataTemplate x:Key="EditingDateTemplate">
                <DatePicker SelectedDate="{Binding PublishDate}"  />
            </DataTemplate>
        </Grid.Resources>
        <DataGrid Name="DG1" ItemsSource="{Binding}" AutoGenerateColumns="False" >
            <DataGrid.Columns>
                <!--Custom column that shows the published date-->
                <DataGridTemplateColumn Header="Publish Date" CellTemplate="{StaticResource DateTemplate}" CellEditingTemplate="{StaticResource EditingDateTemplate}" />
            </DataGrid.Columns>
        </DataGrid>
    </Grid>