Reputation: 11
I want To the calculation inside the grid-view itself.The column1 and column2 display the data ,so in columns 3 it should subtract column2-column1.Column1 and column2 are manual entry only.My question is when the data is entered in both the column the value should reflect in the third column automatically.any idea for this,i didn't try any code for this,i am looking for in which event i have to write the code.
Upvotes: 0
Views: 2617
Reputation: 11
int row = Convert.ToInt32(grid_calc.SelectedIndex.ToString());
object value = (this.grid_calc.Items[row] as DataRowView)[2];
object value1 = (this.grid_calc.Items[row] as DataRowView)[3];
int a = Convert.ToInt16(value);
int b = Convert.ToInt16(value1);
int c = a - b;
(this.grid_calc.Items[row] as DataRowView)[4] = c;
Upvotes: 0
Reputation: 69959
This is a common scenario in WPF and the simplest solution would be to perform the calculation in a data type class rather than in the GridView
. In WPF, we like to create custom classes that implement the INotifyPropertyChanged
interface to hold the properties of our data, rather than using DataTable
s and data bind collections of those classes to the ItemsSource
property.
So if you had a class that represents your data, you could simply add another property to data bind to your third column. Let's say that your custom class properties are named Column1
, Column2
and Column3
. Your properties should look like this to automatically update the third column:
public int Column1
{
get { return column1; }
set
{
column1 = value;
NotifyPropertyChanged("Column1");
NotifyPropertyChanged("Column3");
}
}
public int Column2
{
get { return column2; }
set
{
column2 = value;
NotifyPropertyChanged("Column2");
NotifyPropertyChanged("Column3");
}
}
public int Column3
{
get { return Column2 - Column1; }
}
If you are unfamiliar with data binding, you can find out more about it from the Data Binding Overview page on MSDN.
Upvotes: 1
Reputation: 401
First you'll need an event listener to see if your values in the grid view have changed
so
this.mygridview.CellEndEdit += mygridview_CellEndEdit;
then in the event handler
protected void mygridview_CellEndEdit(object_sender, EventArgs e){
int row_changed = this.mygridview.CurrentCell.RowIndex;
int column1_value = Convert.toInt32(this.mygridview.Rows[row_changed].Cells[0]);
int column2_value = Convert.toInt32(this.mygridview.Rows[row_changed].Cells[1]);
this.mygridview.Rows[row_changed].Cells[2].Value = (column2_value - column1_value ).toString;
All you need to do is check that both columns have numbers and are not null... Just remember that your values will be refreshed if you have some postback or if the gridview has a datasource and the values refresh.. so just be careful..
Upvotes: 0