Reputation: 2227
I have a gridview
which binds data on page load:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindCustomerData();
}
}
I would like to display different buttons depending on the criteria. For simplicity
If its the first gridview row then display "First Record"
If its the last gridview row then display "Last Record"
Any other row "Middle Record"
All buttons start with Visible = False
on the markup.
In my RowDataBound
event i have
protected void gvCusts_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
int lastIndex = gvCusts.Rows.Count -1;
if (e.Row.RowType == DataControlRowType.DataRow)
{
Button buttonFirst = (Button)e.Row.FindControl("buttonFirst");
Button buttonMiddle = (Button)e.Row.FindControl("buttonMiddle");
Button buttonLast = (Button)e.Row.FindControl("buttonLast");
// Customer Records found
if (c.Id > 0)
{
if (e.Row.RowIndex == 0)
{
// First row so display first button only
buttonFirst.Visible = true;
}
else if (e.Row.RowIndex >= 1 && e.Row.RowIndex <= lastIndex)
{
// Not the first row and not the last row so display the middle button only
buttonMiddle.Visible = true;
}
else if (e.Row.RowIndex == lastIndex)
{
// Last row, so display the last button only.
buttonLast.Visible = true;
}
}
}
}
The problem is i cant find a proper way to get the middle and last rows and have buttons showing at the wrong stages.
I then made the int lastIndex = gvCusts.Rows.Count -1;
line of code static
and still not getting the correct results.
I've read a number of articles so obviously i'm missing something somewhere but not sure what?
Upvotes: 0
Views: 2321
Reputation: 752
int rowCount=0;
rowCount= YourDataTable.Rows.Count-1;
protected void gvCusts_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
int lastIndex = rowCount;//rowCount has the last index
if (e.Row.RowType == DataControlRowType.DataRow)
{
Button buttonFirst = (Button)e.Row.FindControl("buttonFirst");
Button buttonMiddle = (Button)e.Row.FindControl("buttonMiddle");
Button buttonLast = (Button)e.Row.FindControl("buttonLast");
// Customer Records found
if (c.Id > 0)
{
if (e.Row.RowIndex == 0)
{
// First row so display first button only
buttonFirst.Visible = true;
}
else if (e.Row.RowIndex >= 1 && e.Row.RowIndex < rowCount)
{
// Not the first row and not the last row so display the middle button only
buttonMiddle.Visible = true;
}
else if (e.Row.RowIndex == rowCount)
{
// Last row, so display the last button only.
buttonLast.Visible = true;
}
}
}
}
Upvotes: 1