I have a situation where I have Multiple GridViews on a page GridView1 – GridView4.
All these GridViews have TextBoxes in the cells, I would like to run a calculation function only on the Column of the TextBox that was Clicked and on that particular GridView.
Example: A user clicks on a TextBox in Column 2 of GridView3 and changes a number value, the OnTextChange event of that particular TextBox should fire to run a calculation and total all the numbers of GridView3 Col2 in a footer label.
I searched and all the other suggestions I found assume you have only 1 grid and that you know what preset Column the calculation is done at IE a prices column, But I don’t know what Column info a user will edit in any of my 4 GridViews.
I gave up and resolved to just running the calculation code on the Entire GridView, not just the column edited, but to do this I need to Get the GridView.ID of the Gridview containing the TextBox. Extensive serches came up with how to get the ID of the sender Item but not the GridView.ID that contains the sender.
If anyone can help with either situation, please do so, I would really appreciate it.
As Per the conversations below, I have edited this post to include the Edited answer provided by Tim in the hopes that others may learn from this code:
//This is working code
protected void textBox_TextChanged(Object sender, EventArgs e)
{
TextBox txt = (TextBox)sender;
GridViewRow gvRow = (GridViewRow)txt.NamingContainer;
GridView Grid = (GridView)gvRow.NamingContainer;
// if you need the index of the column of the TextBox
int colIndex = 0;
for (int i = 0; i < gvRow.Cells.Count; i++)
{
if (gvRow.Cells[i] == txt.Parent)
{
colIndex = i;
Msg.Text = "Col: "+colIndex.ToString();
break;
}
}
int gridNum = 0;
switch (Grid.ID)
{
case "GridView1":
gridNum = 1;
break;
case "GridView2":
gridNum = 2;
break;
case "GridView3":
gridNum = 3;
break;
case "GridView4":
gridNum = 4;
break;
}
Label ColTotal = (Label)Grid.FooterRow.FindControl("G" + gridNum + "TotalPP" + colIndex);
double total = 0;
foreach (GridViewRow row in Grid.Rows)
{
TextBox tb = (TextBox)row.FindControl(txt.ID);
double d;
if (double.TryParse(tb.Text, out d))
total += d;
}
ColTotal.Text = total.ToString();
}
As you can see, according to the way the code is set up, the colIndex will help me find the footer label for each column and put it’s total in.
You could let all
TextBoxeshandle the sameTextChangedevent and use this(untested)code:Of course assuming that all TextBoxes are in
TemplateFieldsand the footerTextBoxhas the same ID. Remember to setAutoPostbackto true if you want to postback immediately.