在WPF中单击按钮时,将文本框中的数据添加到DataGridView

时间:2016-08-04 09:24:45

标签: c# wpf

我的窗口有2个TextBox,一个Button和一个DataGridView,当我点击按钮时,DataGridView需要显示TextBox的值

这就是我现在所拥有的:

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

在这种情况下,DataGrid的行会更新,但不会逐个添加值!

有没有办法在WPF中实现这一目标?

2 个答案:

答案 0 :(得分:4)

您必须将新项目(可能是匿名的)添加到<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean id="customerDAO" class="org.test.JdbcCustomerDAO"> <property name="dataSource" ref="dataSource" /> </bean> </beans> 集合。

例如

<?php
setlocale(LC_ALL, "en_US.utf8"); 
$val = iconv('UTF-8','ASCII//TRANSLIT',$val);
?>

代码

Items

答案 1 :(得分:1)

定义datagrid列 并将数据绑定到相应的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>

背后的代码

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