转自:http://blog.csdn.net/jinjingwen/article/details/6773688
部分前台代码如下:
<EmptyDataTemplate> <table cellspacing="0" rules="all" border="1" style="border-collapse: collapse;"> <tr> <th>Customer_id</th> <th>CustomerName</th> <th>Operate</th> </tr> <tr> <td> <asp:TextBox ID="NewCusID" runat="server"></asp:TextBox> </td> <td> <asp:TextBox ID="NewCusName" runat="server"></asp:TextBox> </td> <td> <asp:Button ID="AddNewBtn" runat="server" Text="Add New Record" onclick="AddNewBtn_Click" /> </td> </tr> </table> </EmptyDataTemplate>
报错:上下文中不存在NewCusID和NewCusName
解决方法:
因为NewCusID和NewCusName在模板列中,所以不能直接使用。应该先使用FindControl找到控件后再取值。
因此后台代码应该按照下面的方式写:
TextBox NewCusIDTextBox = this.form1.FindControl("NewCusID") as TextBox; TextBox NewCusNameTextBox = this.form1.FindControl("NewCusName") as TextBox; string cusID = NewCusIDTextBox.Text.ToString(); string cusName = NewCusNameTextBox.Text;