Tony
Tony

Reputation: 1869

Storing GridViewRow Object between Postback

I'm using the following code to highlight a row the user clicks on in gridview (and unhighlights previously selected row):

    protected void PartListRowClicked(object sender, GridViewRowClickedEventArgs e)
    {
        pnewrow = (GridViewRow)PartList.Rows[e.Row.RowIndex];
        pnewrow.BackColor = Color.Blue;
        pnewrow.ForeColor = Color.White;
        if (poldrow != null)
        {
            poldrow.BackColor = Color.Empty;
            poldrow.ForeColor = Color.Black;
        }
        poldrow = pnewrow;
    }

However, the poldrow object is always reset to null after a postback (clicking causes a postback). Is there a way to save the row index between postbacks? Or alternatively, is there a better way to implement this functionality?

Thanks

Upvotes: 3

Views: 566

Answers (3)

Pilgerstorfer Franz
Pilgerstorfer Franz

Reputation: 8359

Of course it is possible to store the oldRow(index) at the server. For example you may use a ViewState or a Session var. But imo it's a long way to the server and back only to change the color/style of a row. So I would propose to use JQuery to change the style of a row, unless you have to note a rowClicked event on the server?!

<script type="text/javascript" src="js/jquery-1.7.1.js"></script>
<script type="text/javascript">
    var oldRow = null;
    var newRow = null;
    $(document).ready(function () {
        // gvProducts is my gridView
        $("#gvProducts tr:gt(0)").click(function () {
            oldRow = newRow;
            newRow = $(this);

            newRow.css("background-color", "blue");
            newRow.css("color", "white");

            if (oldRow != null) {
                oldRow.css("background-color", "transparent");
                oldRow.css("color", "black");
            }
        });
    });
</script>

Using this script you stay on the client and your clients won't have to make a postback to the server just for setting a style!

Upvotes: 2

gwt
gwt

Reputation: 2413

you can simply save the index into a session or viewstate or cookie ! and after the postback use that value to retrieve what ever you want !

set :

Session["rowindex"]="the index";

get :

string index=Session["rowindex"].ToString();

Upvotes: 0

Alex
Alex

Reputation: 35409

You could store the value in ViewState or Session:

public int CurrentRowIndex
{
    get
    {
        return ViewState["rowindex"] != null ?
               int.Parse(ViewState["rowindex"]) :
               0;
    }

    set
    {
        ViewState["rowindex"] = value;
    }
}

Upvotes: 1

Related Questions