如何在Gridview模板中获取控件类型?

时间:2013-04-29 07:45:01

标签: c# asp.net gridview

如何在ASP.NET中的gridview中获取EditTemplate控件的控件类型?

要获取绑定控件的类型,我只需执行此操作

foreach (TableCell cell in grdViewDetails.Rows[e.RowIndex].Cells)
{               
    //set the employeeid so you can update the dataset
    if (cell.Controls[0] is CheckBox)
    {
       CheckBox check = (CheckBox)cell.Controls[0];
       //Do stuff with the control and the text inside the control etc;
    }
}

但我似乎无法在模板中找到控件。他们只是跳过这个。

我试图无济于事。

foreach (TableCell cell in grdViewDetails.Rows[e.RowIndex].Cells)
{  
    var test1 = cell.Controls[0];
    columnName = dsOriginal.Tables[0].Columns[startOfColumns].ColumnName; //[System.Web.UI.LiteralControl] I can find the Column Name but it't not a normal control... It's a LiteralControl?
    var test2 = cell.FindControl("CheckWeek2");  //[System.Web.UI.WebControls.Calendar] = {SelectedDate = The name 'SelectedData' does not exist in the current context}
}

我的Gridview控件模板

<asp:TemplateField HeaderText="week2" SortExpression="week2">
    <EditItemTemplate>
        <asp:CheckBox ID="CheckWeek2" runat="server" Checked='<%# Bind("week2") %>'></asp:CheckBox>
    </EditItemTemplate>
    <ItemTemplate>
        <asp:CheckBox ID="Label2" runat="server" Enabled="false" Checked='<%# Bind("week2") %>'></asp:CheckBox>
    </ItemTemplate>
</asp:TemplateField>

2 个答案:

答案 0 :(得分:1)

试试这个:

        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            CheckBox CheckWeek2 = (CheckBox)e.Row.FindControl("CheckWeek2");

        }

答案 1 :(得分:1)

尝试以下,

if (this.grdViewDetails.EditIndex != -1)
{
 CheckBox b = grdViewDetails.Rows[grdViewDetails.EditIndex].FindControl("CheckWeek2") as CheckBox;
 if (b != null)
  {
  //do something
  }
}