Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
242 views
in Technique[技术] by (71.8m points)

wpf - c# Set value to a DataRow automatically

What I want to do is to change value of row's forth cell if cell number 3 is changed. I have an EditEnding method for my grid. That's my method below. I don't really know how to finish it

that's the grid definition:

<DataGrid x:Name="dataGrid1"... CellEditEnding="dataGrid1_EditEnding">

and the method:

private void dataGrid1_EditEnding(object sender, DataGridCellEditEndingEventArgs e)
{
    // initializing DataRowView from my datagrid
    DataRowView drv = (DataRowView)dataGrid1.CurrentItem;

    // checking if there were any changes
    if (drv.Row[3, DataRowVersion.Original] != drv.Row[3])
    {
       //set value to cell
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Well, i did my stuff, just forget to post it here.

First I did it with EditEnding event, it looked like that:

private void dataGrid1_EditEnding(object sender, DataGridCellEditEndingEventArgs e)
{
    DataRowView drv = (DataRowView)dataGrid1.CurrentItem;

    if (drv.Row[3, DataRowVersion.Original] != drv.Row[3])
    {
       rowView.Row.SetField(4, /* my logic here */);
    }
}

The problem was it was adding the value only on second edit. Then I changed my idea and added a RowChanged event to my DataTable, which was like that:

    static void dtSP_RowChanged(object sender, DataRowChangeEventArgs e)
    {
        bool temp = false;

        try
        {

            temp = e.Row[4, DataRowVersion.Original] == e.Row[4];
        }
        catch { }

        if (temp && int.Parse(e.Row[3].ToString()) != -1)
        {
            e.Row[4] = (/* my logic */);
        }
    }

The method was going into infinity loop (it was noticing, that fourth row had changed).

And then i saw this: http://www.windowsdevcenter.com/pub/a/dotnet/2003/05/26/datacolumn_expressions.html

I've ended with one line long code:

dtSP.Columns[4].Expression = "expression";

@blindmeis, I forgott to mention I use ADO.NET, sorry


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...