简体   繁体   中英

Add data from Textbox to DataGridView on button click in WPF

My Window has 2 TextBox ,one Button and a DataGridView , when I click the button, the DataGridView need to display the values of TextBox

This is what I have until now:

private void btn_Click(object sender, RoutedEventArgs e)
{

    DataTable dt = new DataTable();
    dt.Columns.Add("id");
    dt.Columns.Add("name");
    DataRow dr = null;

    if (dt.Rows.Count > 0)
    {    
         dr = dt.NewRow();
         dt.Rows.Add(txt1.Text, txt2.Text);
         grid1.ItemsSource = dt.DefaultView;
    }
}

In this case DataGrid 's rows get updated, but not adding values one by one!

Is there a way to accomplish this in WPF?

You have to add the new Item (which could be anonymous) to the Items collection.

Eg;

   <DataGrid x:Name="Dgrd" AutoGenerateColumns="False">
        <DataGrid.Columns>
            <DataGridTextColumn Header="ID" Binding="{Binding ID}"/>
            <DataGridTextColumn Header="NAME" Binding="{Binding NAME}"/>
        </DataGrid.Columns>
    </DataGrid>

Code

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        Dgrd.Items.Add(new { ID = IDTextbox.Text, NAME = NAMETextbox.Text });
    }

define the datagrid columns and bind the data onto that corresponding coloumns

<Grid>
    <TextBox x:Name="txt1" HorizontalAlignment="Left" Height="23" Margin="44,32,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="120"/>
    <TextBox x:Name="txt2"  HorizontalAlignment="Left" Height="23" Margin="204,32,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="120"/>
    <Button Content="Button" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Margin="231,75,0,0" Click="Button_Click"/>
    <DataGrid x:Name="grid1" HorizontalAlignment="Left" Margin="44,138,0,0" VerticalAlignment="Top" Height="139" Width="280">
        <DataGrid.Columns>
            <DataGridTextColumn Header="ID" Binding="{Binding ID}"/>
            <DataGridTextColumn Header="NAME" Binding="{Binding NAME}"/>
        </DataGrid.Columns>
    </DataGrid>

</Grid>

code behind

  private void Button_Click(object sender, RoutedEventArgs e)
    {
         grid1.Items.Add(new { ID = txt1.Text, NAME = txt2.Text });
    }

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