We have 100 records in gridview and we want to select 90th record. But user is not intersted to scroll through mouse and see that record. So in my article I have added linkbuttons dynamically using placeholder.
When I click 90th record automatically scroll to 90th record and display it.
Basically this is used to scroll automatically which record you want ,by clicking linkbutton at the top of the page you can go that record.you need not scroll manually that record. My code goes like
JavaScript code to write
scroll function in client side:
<script type ="text/javascript">
function setscroll()
{
var gridCol = document.getElementById("GridView1").getElementsByTagName("td")
//alert(gridCol.length )
if(gridCol.length > 0)
{
var rowCOunt = 0;
while(rowCOunt < gridCol.length)
{
if(gridCol[rowCOunt].style.backgroundColor=="orange")
{
window.scrollTo(0,gridCol[rowCOunt].offsetTop);
break;
}
rowCOunt +=1;
}
}
}
</script>
Design code
Come to design part:
<body onload="setscroll()">
<form id="form1" runat="server">
<div id="divGrid" style="overflow: auto; height: 130px">
<asp:GridView ID="GridView1" CssClass ="newStyle1 " runat="server" CellPadding="4" ForeColor="#333333"
GridLines="None" Font-Names="Calibri">
<RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
<FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
<HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
</div>
<br />
<br />
<br />
<br />
<br />
<br />
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
Server side code
And My Code behind code is
string constr = ConfigurationManager.ConnectionStrings["narayanaConnectionString"].ConnectionString;
SqlConnection cn;
protected void Page_Load(object sender, EventArgs e)
{
LinkButton lb;
if (!IsPostBack)
{
bind();
}
for (int i = 0; i < GridView1.Rows.Count; i++)
{
lb = new LinkButton();
lb.ID = "LinkButton" + i.ToString();
lb.Text = ""+GridView1.Rows[i].Cells[0].Text;
lb.Font.Name = "Verdana";
PlaceHolder1.Controls.Add(lb);
lb.Click +=new EventHandler(lb_Click);
}
}
protected void lb_Click(object sender, EventArgs e)
{
LinkButton lb = (LinkButton)sender;
int i=Convert.ToInt16 (lb.Text );
GridView1.SelectedIndex = i - 1;
GridView1.SelectedRow.Cells[0].Focus();
GridView1.SelectedRow.Cells[0].BackColor = Color.Orange ;
}
public void bind()
{
cn = new SqlConnection(constr);
SqlDataAdapter da = new SqlDataAdapter("select * from student", cn);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
Conclusion
In client user point of view this is really wonderful. I hope it helps you.
Thank you happy coding