【转】asp.net,报错“上下文中不存在名称‘控件的ID’

转自: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;
本博客所有博文,若无专门说明皆为原创,转载请注明作者和出处!
原文地址:https://www.cnblogs.com/ifinver/p/2945011.html