tshoemake
tshoemake

Reputation: 1351

Needing row&col indices in code behind to get selected gridview cell value

I'm using a gridview to click a cell. Once I click the cell I have a modal box open.

The modal has an Update and Cancel button.
I would like to get the clicked cell's selected row and column indices in the code behind to determine whether the clicked cell has a text value or not.

I'm able to do this in my code behind here:

protected void Grd_RowCommand(object sender, GridViewCommandEventArgs e)
{
    int selectedRowIndex = Convert.ToInt32(e.CommandArgument.ToString());
    int selectedColumnIndex = Convert.ToInt32(Request.Form["__EVENTARGUMENT"].ToString());
}

This is what i have, which i need code for at the help comments:

protected void btnUpdate_Click(object sender, EventArgs e)
{
    int selectedRowIndex = //need help
    int selectedColumnIndex = // need help 

    if (Grd.Rows[selectedRowIndex].Cells[selectedColumnIndex].Text == " ")
    {
        //new, insert into db
    }

    else
    { 
        //update existing db record
    }
}  

Upvotes: 1

Views: 696

Answers (1)

ekad
ekad

Reputation: 14614

You can use ViewState to pass the selected row index and the selected column index between postbacks. Add the following properties to your code behind

private int SelectedRowIndex
{
   get
   {
      if (ViewState["SelectedRowIndex"] == null)
      {
         return 0;
      }
      else
      {
         return (int)ViewState["SelectedRowIndex"];
      }
   }
   set
   {
      ViewState["SelectedRowIndex"] = value;
   }
}

private int SelectedColumnIndex
{
   get
   {
      if (ViewState["SelectedColumnIndex"] == null)
      {
         return 0;
      }
      else
      {
         return (int)ViewState["SelectedColumnIndex"];
      }
   }
   set
   {
      ViewState["SelectedColumnIndex"] = value;
   }
}

then assign the selected row index and the selected column index to the properties above in Grd_RowCommand

protected void Grd_RowCommand(object sender, GridViewCommandEventArgs e)
{
    this.SelectedRowIndex = Convert.ToInt32(e.CommandArgument.ToString());
    this.SelectedColumnIndex = Convert.ToInt32(Request.Form["__EVENTARGUMENT"].ToString());
}

and get the values in btnUpdate_Click

protected void btnUpdate_Click(object sender, EventArgs e)
{
    int selectedRowIndex = this.SelectedRowIndex;
    int selectedColumnIndex = this.SelectedColumnIndex;

    if (Grd.Rows[selectedRowIndex].Cells[selectedColumnIndex].Text == " ")
    {
        //new, insert into db
    }

    else
    { 
        //update existing db record
    }
}  

Upvotes: 1

Related Questions