4

I want to add a button on GridView cell on certain condition. I did the following in RowDatabound event

if( i==0)
{
   Button btn= new Button();
   btn.Text = "view more";        
   e.Row.Cells[7].Controls.Add(btn);
}

When this executes, the text in the cell which is bound is lost and only the button appears. I need to have the button along with the cell text present already.

Can anyone please help me doing this?

mxmissile
  • 11,464
  • 3
  • 53
  • 79
Shanna
  • 753
  • 4
  • 14
  • 34

3 Answers3

6

When you add a control into the cell it trumps the text in the cell and only wants to display the control(s).

You can however have both the text and the button while keeping them separate. To do this you need to add another control in the form of a label:

Label myLabel = new Label();
myLabel.Text = e.Row.Cells[7].Text; //might want to add a space on the end of the Text
e.Row.Cells[7].Controls.Add(myLabel);

LinkButton myLinkButton = new LinkButton();
myLinkButton.Text = "view more";
e.Row.Cells[7].Controls.Add(myLinkButton);
Hugo Yates
  • 2,081
  • 2
  • 26
  • 24
3

It's a workaround, check if it helps you:

You can convert your existing BoundColumn to Linkbuton if it is feasible with your requirement.

if( i==0)
{
    LinkButton lnkbtn = new LinkButton();
    lnkbtn.Text = e.Row.Cells[7].Text;
   // Create a command button and link it to your id    
   // lnkbtn.CommandArgument = e.Row.Cells[0].Text; --Your Id 
   // lnkbtn.CommandName = "NumClick";
   // btn.Text = "view more";        
    e.Row.Cells[7].Controls.Add(lnkbtn);
}
Ethan Shoe
  • 466
  • 1
  • 7
  • 20
Suraj Singh
  • 4,041
  • 1
  • 21
  • 36
  • Is it Possible to retain the text and add the control as well? – Shanna Oct 30 '13 at 05:33
  • @SandraDsouza Can you elaborate a little more about retaining text and control ? – Suraj Singh Oct 30 '13 at 06:09
  • I want to have linkbutton text as "view More". But when I do that the text in the cell[7] is lost. I want to have that text as well – Shanna Oct 30 '13 at 13:46
  • @Sandra Please check updated answer, As per my understanding you can create a command button as in comments above or if you want two buttons then, Create those directly on aspx page and make those `viewmore` button only for selected rows at `RowDatabound` event. – Suraj Singh Oct 31 '13 at 10:00
2

You have to recreate all dynamic controls on every postback. But RowDataBound is executed only if the grid gets databound. So this is not the right approach.

If this is just a single button you should add it declaratively to the aspx in a TemplateField. Then you can switch visibility in RowDataBound.

Tutorial 12: Using TemplateFields in the GridView Control

 Button btn = (Button)e.Row.FindControl("ButtonID");
 btn.Visible = i==0;

You can handle the Click event of the Button for your "view more"-logic.

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939