2017-05-07 43 views
0

我会保持简短 我是一名12年级的软件工程学生,作为我决定制作网站的最终项目。网站的内容并不重要。问题是这样的:在GridView的TemplateField中获取文本框的值

在附图中有一个文本框内的gridview里面的templatefield。我需要获得用户在里面写入的价值。在您输入值后,按购买。我看过类似的问题,但都没有提供可行的解决方案。这个值会消失。我用FindControl找到了正确的控件,但是值被删除了。我怎么知道我在正确的控制下?我去了客户端,并添加到asp:TextBox以下: Text =“5” 这很好用,所以我知道它得到了正确的控制,但有些东西使它消失。我的gridview正在填充两个数据集组合的数据集,我把合并命令和数据源和数据绑定都在if(!this.IsPostBack)。我完全失去了,不知道该怎么做,非常感谢帮助。 The Picture of the Gridview

回答

0

通过使用FindControl搜索正确的行,可以访问GridView中的所有控件。为此,您可以将行号作为CommandArgument发送,并在后面的代码中使用。因此,首先使用OnCommand代替OnClick,并在aspx页面上设置CommandArgument

<asp:TemplateField> 
    <ItemTemplate> 
     <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> 

     <asp:Button ID="Button1" runat="server" Text="Purchase" OnCommand="Button1_Command" CommandArgument='<%# Container.DataItemIndex %>' /> 
    </ItemTemplate> 
</asp:TemplateField> 

然后在后面

代码
protected void Button1_Command(object sender, CommandEventArgs e) 
{ 
    //get the rownumber from the command argument 
    int rowIndex = Convert.ToInt32(e.CommandArgument); 

    //find the textbox in the corrext row with findcontrol 
    TextBox tb = GridView1.Rows[rowIndex].FindControl("TextBox1") as TextBox; 

    //get the value from the textbox 
    try 
    { 
     int numberOfTickets = Convert.ToInt32(tb.Text); 
    } 
    catch 
    { 
     //textbox is empty or not a number 
    } 
} 
相关问题