我有两个嵌套的重复器。在嵌套的重复器的页脚中,我有文本框和文件上传控件。我能够轻松获取文件上传的实例,但是文本框的实例为空,尽管它们都放置在页脚中。
下面是表示内部重复器页脚的aspx部分:
<FooterTemplate>
<tr class="add_comment">
<td>Add comment </td>
</tr>
<tr>
<td>
<asp:TextBox runat="server" Columns="20" Rows="3" ID="comment_txt" TextMode="MultiLine" Width="60%" CssClass="new_comment" ViewStateMode="Inherit"></asp:TextBox>
</td>
</tr>
<tr class="add_comment">
<td>
<asp:FileUpload ID="uploadImageBtn" runat="server" Text="Add image" OnClick="uploadImage" CssClass="comment_buttons" />
<asp:Button ID="comment_btn" runat="server" OnClick="submitComment" Text="Comment" CssClass="comment_buttons" />
</td>
</tr>
</table>
</FooterTemplate>
这是我试图访问控件的C#代码:
protected void commentsRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if ((e.Item.ItemType == ListItemType.Footer ))
{
Repeater childRepeater = (Repeater)sender;
TextBox commentTextBox = (TextBox)e.Item.FindControl("comment_txt");
String postText = commentTextBox.Text.ToString();
FileUpload upFile = (FileUpload)e.Item.FindControl("uploadImageBtn");
}
}
当运行页面时,我遇到了这个错误:
Object reference not set to an instance of an object
由于这行代码的存在导致了这个问题:
String postText = commentTextBox.Text.ToString();
我尝试删除文本框代码,只检索上传文件,结果非常好。问题在于访问文本框。
编辑:应该在同一页的按钮的onclick
事件处理程序中访问文本框的访问文本和上传按钮的实例。因此,我定义了两个全局变量,在执行Repeater的某些嵌套重复器事件(例如ItemDataBound或由Adrian Iftode建议的事件ItemCreated)时分配它们的值。然后,在按钮的onclick中使用它们,假设它们具有值,因为嵌套的repeater事件应在按钮的 onclick之前触发。成功检索上传文件实例,但始终为空的文本框。
全局变量声明:
TextBox commentTextBox;
FileUpload upFile;
Repeater childRepeater;
String postText;
嵌套重复器事件内的代码:
protected void commentsRepeater_ItemCreated(object sender, RepeaterItemEventArgs e)
{
if ((e.Item.ItemType == ListItemType.Footer))
{
childRepeater = (Repeater)sender;
commentTextBox = (TextBox)(e.Item.FindControl("comment_txt"));
postText = commentTextBox.Text.ToString();
upFile = (FileUpload)e.Item.FindControl("uploadImageBtn");
}
}
点击事件内的代码:
protected void submitComment(object sender, EventArgs e)
{
Boolean insert = true;
if (upFile.HasFile || !String.IsNullOrEmpty(postText))
{
//some code.
}
上述if语句仅在upFile有文件时执行,postText始终被视为null。
请问有谁能帮我解决这个错误吗?
谢谢。