Javascript实现GridView无刷新选择一行

Javascript可以实现对GridView中某一行选择,而无需进行页面的刷新。

首先要在GridViewonrowdataboundevent handler中为GridView中的每一行onclick绑定event handler (Javascript)。假如GridView代码如下:

        <asp:GridView runat="server" id="GridViewCategory" AutoGenerateColumns="False"

    Width="100%" BackColor="#CCCCCC" BorderColor="#999999" BorderStyle="Solid"

    BorderWidth="3px" CellPadding="4" CellSpacing="2"

ForeColor="Black" onrowdatabound="GridViewCategory_RowDataBound">

        <RowStyle BackColor="White" />

        <Columns>

            <asp:BoundField DataField="Description" HeaderText="Category" />

        Columns>

        <FooterStyle BackColor="#CCCCCC" />

        <PagerStyle BackColor="#CCCCCC" ForeColor="Black" HorizontalAlign="Left" />                       

        <HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />

asp:GridView>

onrowdataboundevent handler代码如下:

        protected void GridViewCategory_RowDataBound(object sender, GridViewRowEventArgs e)

        {

            try

            {

                if (e.Row.RowType == DataControlRowType.DataRow)

                {

                    e.Row.ID = e.Row.Cells[0].Text;

                    e.Row.Attributes.Add("onclick", "GridView_selectRow(this, '" + e.Row.Cells[0].Text + "')");

                }

            }

            catch (Exception ex)

            {

                throw new ApplicationException(ex.Message);

            }

        }

最后,GridView中每一行的onclick event handlerJavascript代码如下:

<script type="text/javascript">  

    var lastRowSelected;   

    function GridView_selectRow(row, description) {

        if (lastRowSelected != row) {

            if (lastRowSelected != null) {

                lastRowSelected.style.backgroundColor = 'White';

                lastRowSelected.style.color = 'Black';

            }

        }

        row.style.backgroundColor = '#000099';

        row.style.color = 'White';

        lastRowSelected = row;

        document.getElementById("<%=TextBoxCategory.ClientID%>").value = description;

    }

script>

 

 

 

Javascript实现GridView无刷新选择一行_第1张图片

你可能感兴趣的:(Asp.net,javascript,exception,asp,function,object,server)