Friday, November 18, 2011

Scroll to particular record in GridView

Hello Friends,
here is a tip to scroll the gridview to particular record.
the basic concept is html scrolling. to scroll at particular position create an anchor tag with name as address (eg. #ScrollPoint '# is must')

now redirect the page to the location using javascript call
window.location.href = "#ScrollPoint";

 
same thing can be achieved by anchorlink href
here is sample code

HTML Page
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="return MoveTo();" />
    <div style="height: 100px; overflow: auto;">
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
            <Columns>
                <asp:TemplateField HeaderText="ID" SortExpression="ID">
                    <EditItemTemplate>
                        <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("ID") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <a name='<%# Eval("ID") %>'></a>
                        <asp:Label ID="Label1" runat="server" Text='<%# Bind("ID") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
            </Columns>
        </asp:GridView>
    </div>  


<script type="text/javascript">
        function MoveTo() {
            window.location.href = "#" + document.getElementById('<%= TextBox2.ClientID %>').value;
            return false;
        }
    </script>

Code Behind
protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindControls();
            }
        }

        private void BindControls()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("ID");
            dt.Columns.Add("Name");
            for (int i = 0; i < 200; i++)
            {
                AddRow(dt);    
            }


            GridView1.DataSource = dt;
            GridView1.DataBind();

        }

        private static void AddRow(DataTable dt)
        {
            DataRow dr = dt.NewRow();
            dr["ID"] = dt.Rows.Count + 1;
            dr["Name"] = "Sandeep" + dt.Rows.Count + 1;
            dt.Rows.Add(dr);
        }
    }
Happy Coding...

2 comments:

Bhavik solucky said...

great

Lalit M. Oza said...

Very Good Work with the spirit of sharing... Keep it up..