change array values in method
I encountered a bit strange behaviour that I could not understand I wonder if someone can help me understand it.
The follwing method recives an object array and make some changes in the array members public static void adjustRow(object[] row, String column)
{
Double price ,units ,invest;
if (!(Double.TryParse(row[3].ToString(),out price)
& Double.TryParse(row[4].ToString(),out units)
& Double.TryParse(row[5].ToString(),out invest)))
return ;
开发者_开发技巧 switch (column)
{
case INVEST: row[4] = Math.Round(invest / price,2); break;
case UNITS:
case PRICE: row[5] = Math.Round(units * price,2); break;
}
}
the follwing method call the above method:
void editGrids_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
DataGridView gridView = sender as DataGridView;
DataTable source= null;
if (gridView != null)source = gridView.DataSource as DataTable;
if (source != null)
Systm.adjustRow(source.Rows[e.RowIndex].ItemArray,gridView.Columns [e.ColumnIndex].HeaderText);
}
I expected that the values in the input array will be changed outside of the first method scope as well but the actual result is that the values remain the same any explanation?
Thanks Eranany explanation
Sure, I can think of lots of explanations.
1) gridView is null.
2) gridView.DataSource is not a DataTable
3) One of the calls to TryParse is returning false. (Note: you probably meant to use &&, not &.)
4) Column does not match INVEST, UNITS, or PRICE.
5) The value written into the array is the same value as was already there.
Any of the above would explain your observation.
You need to pass array by reference, not by value
http://msdn.microsoft.com/en-us/library/0f66670z%28VS.71%29.aspx
精彩评论