2013-10-29 129 views
3

我想在某些情况下在GridView单元格上添加一个按钮。 我的确在RowDataBound事件以下将控件添加到Gridview单元格

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

当这个执行,似乎这势必会丢失,只有按钮,在单元格中的文本。 我需要将按钮和单元格文本一起存在。

任何人都可以帮我做这件事吗? 在前提前感谢

回答

3

它的解决方法,检查是否可以帮助你

您可以将现有的绑定列转换为Linkbuton它是否与您的要求是可行的。

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); 
} 
+0

非常感谢你:) – Shanna

+0

是否有可能保留文本并添加控件? – Shanna

+0

@SandraDsouza你能详细阐述一下保留文本和控制吗? –

2

您必须在每次回发时重新创建所有动态控件。但是RowDataBound仅在网格获得数据绑定时才执行。所以这不是正确的方法。

如果这只是一个按钮,您应该将其声明添加到TemplateField中的aspx中。然后你可以在RowDataBound中切换可视性。

Tutorial 12: Using TemplateFields in the GridView Control

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

您可以处理Click事件Button为您的 “查看更多” 编辑逻辑。

+0

我已经自动生成列=真 – Shanna

+0

@SandraDsouza:然后改变:) –

4

当您将控件添加到单元格中时,它会超过单元格中的文本并且只想显示控件。

但是,您可以同时保留文本和按钮,并将它们分开。要做到这一点,你需要添加另一个控制标签的形式:

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); 
相关问题