Search code examples
wpfdatagridtextbox

How to create a specified number of columns in a data grid from text box wpf


I want to be able to write a number (preferably only from 1-10) in a textbox and create that certain number of columns for it in a data grid. How would I be able to do that? This is what I've got so far:

<DataGrid x:Name="Tasks" AutoGenerateColumns="False" HorizontalAlignment="Left" Height="345" Margin="244,38,0,0" VerticalAlignment="Top" Width="528" Background="Transparent" HorizontalGridLinesBrush="Transparent" VerticalGridLinesBrush="Transparent" RowBackground="#202020" AlternatingRowBackground="#262626">
        <DataGrid.Columns>
            <DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
            <DataGridTextColumn Header="Words" Binding="{Binding Keywords}"/>
            <DataGridTextColumn Header="Colour" Binding="{Binding Colour}"/>
            <DataGridTextColumn Header="Size" Binding="{Binding Size}"/>
        </DataGrid.Columns>
    </DataGrid>

That is my grid that I have, which on the click of a button simply reads the data from a series of textboxes. Then I have the textbox I want that will be able to modify the number of columns the datagrid creates:

<TextBox x:Name="noColumns" Height="26" Margin="88,244,663.6,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top"/>

I have no idea on how to make it so any help would be appreciated!


Solution

  • This should get your started on the right track.

    First you need to capture the number entered into the TextBox. Let's use the LostFocus event in this example.

    //Add LostFocuse Event Handler
    //Your other properties have been removed for the sake of example brevity
    <TextBox x:Name="noColumns" LostFocus="TextBox_LostFocus"/>
    

    Ok, now let's extract the number from the textbox, and dynamically create columns for your datagrid.

    private void TextBox_LostFocus(object sender, RoutedEventArgs e)
    {
        int columns;
    
        //Determine if TextBox text is number. If so, add columns
        if (int.TryParse(noColumns.Text, out columns))
        {
             for(int x=1; x<=columns; x++)
             {
                  //Add column with header.
                  Tasks.Columns.Add(new DataGridTextColumn() { Header = string.Format("COL: {0}", x) });
             }
        }
    }