0

I have DataRow from grid and I need to modify few columns in one row. So I put all my columns in Array, and tried to modify them but it doesn't work as I wish. I need an explanation for that.

My goal is to get all columns in specific order in Array or some collection, and then modify them etc. I think I am now creating some new objects which reference to something else than my column. Maybe I should try to store in collection some references? Using ref should is best option?

DataRow dr = rows[i] as DataRow;
dr["size"] = 5000; // => size is 5000;
ChangeSize(dr); // => size is 6000;

ChangeSize body

private void ChangeSize(DataRow dataRow)
{
             dataRow["size"] = 6000; // => size is 6000
             Object[] arrayOfColumns= { dataRow["size"], ... };
             arrayOfColumns[0] = 7000; // => won't change size...

}

2 Answers 2

1

You're just changing the value in the array. You happened to initialize that via dataRow["size"] but that doesn't mean there's any perpetual link between the two.

If you need changes to be reflected back to the DataRow, I suspect you should have another method to do that:

private void CopyToDataRow(Object[] source, DataRow target)
{
    target["size"] = source[0];
    // etc
}

There's no concept of triggering custom code like this whenever an array is modified - you'll need to call it at the appropriate time. (And no, ref wouldn't help you here at all.)

Sign up to request clarification or add additional context in comments.

1 Comment

I use that method in my application. It's good to hear that ref won't help.
1

dataRow["size"] contains an int which is a value type.

When you instanciate and intialize arrayOfColumns you get a copy of the value contained at dataRow["size"] and not a reference.

2 Comments

Is there any way to initialize Array with ref to that object? Or I should just copy the value like Jon Skeet write below?
In that case, you can't use ref. As Jon Skeet noticed, you should use an extra method to update the value

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.