2016-12-26 99 views
1

我有一个显示来自SQL数据源(存储过程)的数据来一个gridview,我想一个checkboxex列添加到它,这里是我的代码:一个复选框列添加到GridView

TemplateField field = new TemplateField(); 
 
field.HeaderText = "Exporter ?"; 
 
gv.Columns.Add(field); 
 
CheckBox cb = new CheckBox(); 
 
cb.Visible = true;

问题是,我不知道如何添加一个复选框到我添加到我的gridview列的TemplateField。

+0

看看这里:http://stackoverflow.com/questions/12581088/how-to-add-templatefield-programmatically – Mehmet

回答

0

您可以将代码添加到GridView

<asp:templatefield HeaderText="Check Box"> 
    <itemtemplate> 
     <asp:checkbox ID="cb" runat="server"></asp:checkbox> 
    </itemtemplate> 
</asp:templatefield> 
+0

谢谢,我也希望包含复选框的列在默认情况下不可见,以编程方式使其在运行时可见,我不知道如何做第二部分,因为我无法将ID属性添加到templatefield或itemtemplate标签中? – Platus

+0

我相信** Gounder **有答案。 – Null

1

1)将下面的代码添加到GridView列中。

<asp:TemplateField HeaderText="CheckBoxColumn" Visible="False"> 
      <ItemTemplate> 
       <asp:CheckBox ID="checkBox" runat="server"></asp:CheckBox>     
      </ItemTemplate> 
</asp:TemplateField> 

2)使复选框列可见动态通过添加OnRowDataBound事件或只是通过GridView.Rows

int indexOfCBColumn = 0; 
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) 
{ 
    e.Row.Cells[indexOfCBColumn].Visible = true; 
} 



foreach(GridViewRow row in GridView1.Rows) { 
    if(row.RowType == DataControlRowType.DataRow) { 
     row.Cells[indexOfCBColumn].Visible = true; 
    } 
} 

由于循环!!