((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;
//返回值是\r\n
  string s5 = ((TextBox)(GridView1.Rows[GridView1.EditIndex].Cells[1].FindControl("TextBox2"))).Text;
//返回值是“我的序号”
  string s6 = ((LiteralControl)(GridView1.Rows[GridView1.EditIndex].Cells[1].Controls[2])).Text;
//返回值是\r\n

也就是说其实网上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]其实是等效的。

 

转载于:https://www.cnblogs.com/lyichemistry/p/8503943.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值