zoukankan      html  css  js  c++  java
  • ((TextBox)(GridView1.Rows[GridView1.EditIndex].Cells[1].Controls[0])).Text; 转换出错、获取不到值的解析 Asp.net

                                 <asp:TemplateField HeaderText="序号">
                                          <EditItemTemplate>
                                              <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("序号") %>' Width="64"></asp:TextBox>
                                          </EditItemTemplate>
                                          <ItemTemplate>
                                              <asp:Label ID="Label2" runat="server" Text='<%# Bind("序号") %>' Width="68"></asp:Label>
                                          </ItemTemplate>
                                </asp:TemplateField>
    string s0 = GridView1.Rows[GridView1.EditIndex].Cells[1].Controls[0].GetType().ToString();
    //{Name = "LiteralControl" FullName = "System.Web.UI.LiteralControl"}
    
    string s1 = GridView1.Rows[GridView1.EditIndex].Cells[1].Controls[1].GetType().ToString();
    //{Name = "TextBox" FullName = "System.Web.UI.WebControls.TextBox"}
    
    string s2 = GridView1.Rows[GridView1.EditIndex].Cells[1].Controls[2].GetType().ToString();
    //{Name = "LiteralControl" FullName = "System.Web.UI.LiteralControl"}

    事实上 html中设计是textbox, 但是编译器在内部给添加了两个LiteralControl类。返回值如下:

     string s4 = ((LiteralControl)(GridView1.Rows[GridView1.EditIndex].Cells[1].Controls[0])).Text;
    //返回值是
    
      string s5 = ((TextBox)(GridView1.Rows[GridView1.EditIndex].Cells[1].FindControl("TextBox2"))).Text;
    //返回值是“我的序号”
      string s6 = ((LiteralControl)(GridView1.Rows[GridView1.EditIndex].Cells[1].Controls[2])).Text;
    //返回值是
    

    也就是说其实网上bbs常见的提问里的解决方法用的

    string s9 = ((TextBox)(GridView1.Rows[GridView1.EditIndex].Cells[1].Controls[0])).Text;
    //常见的强制类型转换出错且获取不到控件的原因是序号不对,而这个在MSDN里是没有说明的
    
    string s10 = ((TextBox)(GridView1.Rows[GridView1.EditIndex].Cells[1].Controls[1])).Text;
    //应该用.Controls[1]


    还有一种方法是:

    string s4= ((TextBox)(GridView1.Rows[GridView1.EditIndex].Cells[1].Controls[1])).Text;
    //当存在多个控件 的时候可以尝试用gettype方法看一下哪个是你需要的textbox控件。
    string s5 = ((TextBox)(GridView1.Rows[GridView1.EditIndex].Cells[1].FindControl("TextBox2"))).Text;
    //这个方法与上述的Controls[1]其实是等效的。
  • 相关阅读:
    spring mvc poi excel
    select onchange事件的使用
    eclipse下svn的分支与合并指南
    jquery_final
    ListView
    资源的使用
    Notification
    单选
    复选框
    调试
  • 原文地址:https://www.cnblogs.com/lyichemistry/p/8503943.html
Copyright © 2011-2022 走看看