Skip to main content
 首页 » 编程设计

c#之asp.net datagrid findcontrol 为文本框返回 null

2024年02月23日13findumars

在 ASP.Net 数据网格中,我放置了一个下拉菜单和一个文本框(多行)。我需要循环读取这些值。我正在使用 findControl 方法获取下拉列表的引用对象,但是当我尝试文本框时,它返回 null。

这是我的aspx代码

..... 
 <asp:TemplateColumn> 
            <HeaderTemplate> 
                <asp:DropDownList  
                    ID="HeaderDropDown" Runat="server"  
                    AutoPostBack="True"  
                     OnSelectedIndexChanged="DropDown_SelectedIndexChanged" /> 
            </HeaderTemplate> 
            <ItemTemplate> 
                <asp:DropDownList  
                    ID="ItemDropDown" Runat="server"/> 
            </ItemTemplate> 
        </asp:TemplateColumn> 
          <asp:TemplateColumn > 
          <HeaderTemplate> 
            Details 
            </HeaderTemplate> 
 
        <ItemTemplate> 
 
        <asp:TextBox ID="txtDetails" runat="server"  TextMode="MultiLine"></asp:TextBox> 
 
        </ItemTemplate>        
         </asp:TemplateColumn> 
............... 

C#代码是

 for (int i = 1; i < DataGrid1.Items.Count; i++) 
        { 
            DropDownList lst = DataGrid1.Items[i].Cells[1].FindControl("ItemDropDown") as DropDownList; 
            String value = lst.SelectedValue; 
            String StaffId = DataGrid1.Items[i].Cells[0].Text; 
            TextBox txt= DataGrid1.Items[i].Cells[2].FindControl("txtDetaills") as TextBox; 
         } 

我正在正确获取 lst 对象,但 txt 总是返回 null。

请您参考如下方法:

你有一个错字:

TextBox txt= DataGrid1.Items[i].Cells[2].FindControl("txtDetaills") as TextBox; 

应该是:

TextBox txt= DataGrid1.Items[i].Cells[2].FindControl("txtDetails") as TextBox; 

因此,txtDetaills应该是txtDetails