1

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?

2 Answers 2

4

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 });
    }
Sign up to request clarification or add additional context in comments.

Comments

1

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 });
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.