第一次碰到這樣的錯誤。
部分前臺代碼如下:
<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;