访问详细信息视图中的文本框
有谁知道如何在 DetailsView 字段(c#)内设置文本框的文本?
我尝试了一些变体,但所有变体都返回脱离上下文和对象引用未设置错误。
这是我的代码...
ASPX:
<asp:DetailsView ID="DetailsView1" runat="server" Height="50px" Width="125px">
<Fields>
<asp:TemplateField HeaderText="Header Text">
<InsertItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text="test"></asp:TextBox>
</InsertItemTemplate>
</asp:TemplateField>
</Fields>
</asp:DetailsView>
CS:
TextBox txt = (TextBox)DetailsView1.FindControl("TextBox1");
txt.Text = "Text ";
干杯
Does anyone have any idea how I can set the text of a textbox inside a DetailsView field (c#)?
I've tried a few variations but all return out of context and object reference not set errors.
Heres my code...
ASPX:
<asp:DetailsView ID="DetailsView1" runat="server" Height="50px" Width="125px">
<Fields>
<asp:TemplateField HeaderText="Header Text">
<InsertItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text="test"></asp:TextBox>
</InsertItemTemplate>
</asp:TemplateField>
</Fields>
</asp:DetailsView>
CS:
TextBox txt = (TextBox)DetailsView1.FindControl("TextBox1");
txt.Text = "Text ";
Cheers
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
该错误可能意味着您的
DetailsView
中还没有任何内容。我敢打赌,如果您将其放入代码中:您会看到
txt
实际上是null
- 这是因为FindControl
方法在DetailsView
中未找到任何名为“TextBox1”的内容。您需要将此代码移动到您知道
DetailsView
已填充的位置(如果它绑定到DataSource
,您可以在DataBound<
DetailsView
的 /code> 事件)。另外,我注意到您的
TextBox
位于InsertItemTemplate
中。在默认情况下将DetailsView
置于编辑模式之前,您不会找到TextBox1
:
希望这会有所帮助。
That error likely means that there is nothing in your
DetailsView
yet. I bet if you put this in your code:You'll see that
txt
is, in fact,null
- this is because theFindControl
method didn't find anything named "TextBox1" in theDetailsView
.You need to move this code to a point where you know the
DetailsView
has been populated (if it's bound to aDataSource
, you could do this in theDataBound
event of yourDetailsView
).Also, I noticed that your
TextBox
is in anInsertItemTemplate
. You won't find thatTextBox1
until you put theDetailsView
in edit mode, either by default:Or in code behind:
Hopefully that helps.
@jadarnel27 感谢您提供有关将代码放入 DataBound 事件中的信息。我遇到了类似的问题,文本框值只能通过按钮单击事件传递到 DetailsView 字段 (DefaultMode=Insert)。我不想/不需要按钮。
我的场景:代码标识是否需要详细视图(用于插入)。如果根据从下拉控件中选择的人员不存在记录,则其 PersonID 会预加载到详细信息视图的人员字段中。
使用 FindControl 不起作用,但使用以下代码在放入 DataBound 控件时起作用。
我希望这可以帮助像我这样的另一个新手。
@jadarnel27 thank you for your information about putting the code in DataBound event. I had similar issue where a textbox value would only pass to DetailsView field (DefaultMode=Insert) with a button click event. I didn't want/need a button.
My scenario: code identifies if detailsview is needed (for insert). If record does not exist based on person selected from dropdown control, their PersonID is preloaded into the Person field of detailsview.
Using FindControl didn't work but using the following code did WHEN put in DataBound control.
I hope this helps another newbie like me.