Rocky
Rocky

Reputation: 4524

How to disable and Enable ItemTemplate LinkButton based on GridView first and last row?

I have a gridview with text boxs and two LinkButton Up and Down, I want to make the LinkButton Up and down as Disable, The condition is, Linkbutton Up must be disable for the first row and Linkbutton Down must be disable for the last row.

I am trying to do in onRowDataBound.. But I am unable to do..

foreach (GridViewRow row in GridView1.Rows)
{
  // some code?
}

Please some one tell me how to do that.. with some test exp.

Upvotes: 1

Views: 6026

Answers (3)

Brissles
Brissles

Reputation: 3891

I wouldn't do it in the OnRowDataBound event, I would disable the controls after the GridView has been bound:

// Bind
gv.DataSource = datasource;
gv.DataBind();

// Disable Up/Down LinkButtons
if (gv.Rows.Count > 0)
{
    // With FindControl() if you know the IDs:
    ((LinkButton)gv.Rows[0].Cells[0].FindControl("lb_up").Enabled = false; // Disable up LinkButton 
    ((LinkButton)gv.Rows[gv.Rows.Count - 1].Cells[0].FindControl("lb_down").Enabled = false; // Disable down LinkButton 

    // -- OR --

    // Directly index the controls, assuming Up is at 0, and Down is at 1:
    ((LinkButton)gv.Rows[0].Cells[0].Controls[0]).Enabled = false; // Disable up LinkButton 
    ((LinkButton)gv.Rows[gv.Rows.Count - 1].Cells[0].Controls[1]).Enabled = false; // Disable down LinkButton 
}

You could use either the FindControl method or just directly index the controls.

Upvotes: 2

4b0
4b0

Reputation: 22323

You do same task when You bind your grid like this.Assuming that your link are inside a asp:TemplateField.

 if (GridView1.PageIndex == 0)
  {
     GridView1.Rows[0].FindControl("lnkUp").Visible = false;

  }
  if (GridView1.PageIndex == (GridView1.PageCount - 1))
  {
      GridView1.Rows[GridView1.Rows.Count - 1].FindControl("lnkDown").Visible = false;
  }

Upvotes: 0

KV Prajapati
KV Prajapati

Reputation: 94645

You need to compare RowType in RowDataBound event. Something like this:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    GridViewRow row = e.Row;
    if (row.RowType == DataControlRowType.DataRow)
    {
        .....
    }
}

You may add Down and Up buttons in HeaderTemplate and FooterTemplate respectively.

if (row.RowType == DataControlRowType.Header)
    {
    }

if (row.RowType == DataControlRowType.Footer)
    {
    }

Upvotes: 0

Related Questions