简体   繁体   中英

Get cell content of WPF DataGrid on CurrentCellChanged

I have a WPF DataGrid . I want to get the cell value after user edits it. The DataGrid is already populated with data. User can edit previous data. To save data i want to get cell data from a event handler

Give me a simple code to do it. Suggest one event handler .

You can use the CellEditEnding event to get notified whenever a user has edited a cell.

This simple program illustrates it:

XAML

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApplication1"
        Title="MainWindow" Height="500" Width="500">
    <Grid>
        <DataGrid x:Name="grid" CellEditEnding="cellEditEnding" />
    </Grid>
</Window>

Code-behind

public partial class MainWindow : Window
{
    public class MyClass
    {
        public string Prop1 { get; set; }
        public string Prop2 { get; set; }
        public string Prop3 { get; set; }
    }

    public MainWindow()
    {
        InitializeComponent();

        var objects = new[] 
        { 
            new MyClass { Prop1 = "Object1", Prop2 = "Test1", Prop3 = "Hello" },
            new MyClass { Prop1 = "Object2", Prop2 = "Test2", Prop3 = "Goodbye" },
            new MyClass { Prop1 = "Object3", Prop2 = "Test3", Prop3 = "Welcome" }
        };

        grid.ItemsSource = objects;
    }

    private void cellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
    {
        //Only handles cases where the cell contains a TextBox
        var editedTextbox = e.EditingElement as TextBox;

        if (editedTextbox != null)
            MessageBox.Show("Value after edit: " + editedTextbox.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