如何使用OleDB更新Datagrid?

时间:2017-03-22 10:15:56

标签: c# wpf datagrid oledb

我使用以下代码填充我的datagrid dgFolien:

connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "SELECT Hersteller,Serie,Farbe,[EK-Preis] FROM Folien";

command.ExecuteNonQuery();

OleDbDataAdapter dataAdp = new OleDbDataAdapter(command);
DataTable dt = new DataTable("Folien");
dataAdp.Fill(dt);
dgFolien.ItemsSource = dt.DefaultView;
dataAdp.Update(dt);

connection.Close();

现在我的问题:用户应该只需双击一个单元格,编辑值,离开单元格,表格应该在我的数据库中更新。

我该如何处理?

我发现它可以与RowEditEnding一起使用,但我不知道更新数据库的代码。

任何人都可以帮助我?

2 个答案:

答案 0 :(得分:1)

尝试处理类似这样的事件:

private void dgFolien_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e)
{
    DataRowView drv = e.Row.DataContext as DataRowView;
    if (drv != null)
    {
        using (OleDbConnection conn = new OleDbConnection("yourConnectionString..."))
        {
            conn.Open();
            OleDbCommand cmd = conn.CreateCommand();
            cmd.Parameters.Add(new OleDbParameter("@var1", drv["Hersteller"].ToString()));
            cmd.Parameters.Add(new OleDbParameter("@var2", drv["Serie"].ToString()));
            cmd.Parameters.Add(new OleDbParameter("@var3", drv["Farbe"].ToString()));
            cmd.Parameters.Add(new OleDbParameter("@var4", drv["EK-Preis"].ToString()));


            cmd.CommandText = "UPDATE Folien SET Hersteller=@var1, Serie=@var2, Farbe=@var3 WHERE [EK-Preis] = @var4";
            cmd.ExecuteNonQuery();
        }
    }
}

另外,请确保在XAML标记中将绑定的UpdateSourceTrigger属性设置为PropertyChanged,以便立即设置列值:Datagrid.RowEditEnding doesn't return the update value

<DataGrid x:Name="dgFolien" AutoGenerateColumns="False" CanUserAddRows="False" HorizontalAlignment="Left" 
                  Height="268" Margin="10,138,0,0" VerticalAlignment="Top" Width="489" ColumnWidth="*" RowEditEnding="dgFolien_RowEditEnding">
    <DataGrid.Columns>
        <DataGridTextColumn Header="Hersteller" Binding="{Binding Hersteller, UpdateSourceTrigger=PropertyChanged}" />
        <DataGridTextColumn Header="Serie" Binding="{Binding Serie, UpdateSourceTrigger=PropertyChanged}" />
        <DataGridTextColumn Header="Farbe" Binding="{Binding Farbe, UpdateSourceTrigger=PropertyChanged}" />
        <DataGridTextColumn Header="EK-Preis" Binding="{Binding EK-Preis, UpdateSourceTrigger=PropertyChanged}" />
    </DataGrid.Columns>
</DataGrid>

答案 1 :(得分:0)

几乎相同的代码。您应该在RowEditEnding

中使用SQL命令UPDATE