What is the purpose of getting the RowIndex? To perform a database update to that particular row? Or to calculate the vertical / horizontal total? Is the TextBox shown on editing mode or normal mode? These information may help others to understand your problem clearer.
1. Simply to get the vertical total
RowIndex is not essential if the purpose is to get the vertical total. You can recalculate the total every time the button is clicked. The process should not be expensive (I guess so). The following codes may not suit to your case, but should be good enough to illustrate the idea:
- TextBox txt;
-
int total = 0;
-
foreach (GridViewRow row in gv.Rows)
-
{
-
txt = row.FindControl("txtSomething") as TextBox;
-
total += int.Parse(txt.Text);
-
}
-
lblTotal.Text = total.ToString();
2. Simply to get the horizontal total
Similar concept as (1). Just loop through the GridViewRowCollection and calculate the horizontal total for each row. Do it every time the button is clicked. RowIndex is not essential.
3. Get the RowIndex
If it is still necessary to get the RowIndex, here is my solution: Let me assume that you would like to know the RowIndex of the row(s) on which the TextBox(es)' value has been changed. The TextBox(es) appear on normal mode and is placed within a TemplateField.
Firstly, create a global List of integers. This is used to keep track of the RowIndex. I assume that you would like to keep track of multiple RowIndex as the user may change more than one TextBox value at a time.
- List<int> list = new List<int>();
Then, create the TextChanged event handler for the TextBox. The TextBox's AutoPostBack property should be retained as "False". I assume that you do not want to perform any action before the button is clicked.
- private void txtSomething_TextChanged(object sender, EventArgs e)
-
{
-
TextBox txt = sender as TextBox;
-
GridViewRow row = txt.Parent.Parent as GridViewRow;
-
list.Add(row.RowIndex);
-
}
txt.Parent --> The cell containing the TextBox.
txt.Parent.Parent --> The row containing the cell which containing the TextBox.
Finally, at the button's Click event handler, access the RowIndex from the global List of integers. The list should already been filled with RowIndex since, in this case, TextChanged event handler will be executed before Click event handler.
- private void btnSomething_Click(object sender, EventArgs e)
-
{
-
foreach (int i in list)
-
{
-
// The RowIndex can be accessed through variable i.
-
}
-
}
After all, this may not suit to your case. However, it is good to share ideas... : )