saraa saraa - 2 months ago 27
C# Question

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?

Answer

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