代码隐藏功能中的Cant访问按钮 [英] Cant access button in codebehind
问题描述
.aspx文件中有此按钮,我想在.aspx.cs文件的codeBehind中访问它.
I have this button in my .aspx file and would like to access it in my codeBehind .aspx.cs file.
它在ListView中,所以我假设这就是问题所在(我没有问题可以访问该ListView之外的任何元素)-似乎无法弄清楚.
It's in a ListView so I'm assuming that's where the issue is (I have no problem accessing any elements outside of that ListView) - just cant seem to figure it out.
按钮代码(在ID为lvInstructorList的ListView中):
Button code (Its in a ListView with ID lvInstructorList):
<div class="col-3 checkInBtnDiv" runat="server">
<asp:Button class="checkInBtn" ID="checkInBtn" runat="server" OnClick="CheckInBtn_Click" Text="Check-In"></asp:Button>
</div>
到目前为止我在代码中尝试过的东西:1)
What I've tried so far in codeBehind: 1)
protected void CheckInBtn_Click(object sender, EventArgs e)
{
(lvInstructors.FindControl("checkInBtn") as Button).Text = "New text";
}
2)
protected void CheckInBtn_Click(object sender, EventArgs e)
{
var ctrl = (Control)sender;
var lvi = (ListViewItem)ctrl.NamingContainer;
var checkInBtn = (IButtonControl)lvi.FindControl("checkInBtn");
checkInBtn.Text = "New Text";
}
,但是这些选项都不起作用.有什么想法/提示吗?谢谢!
but neither of these options have worked. Any ideas/tips? Thank You!
这里是我的整个ListView:
Heres my entire ListView:
<asp:ListView
ID="lvInstructors"
runat="server"
AutoGenerateColumns="False"
ShowRegularGridWhenEmpty="False"
EmptyDataText="No Sessions to Display."
OnRowDataBound="lvDataBound"
OnRowCommand="lvCommand"
Visible="true">
<LayoutTemplate>
<div class="container" id="mainContent">
<asp:PlaceHolder ID="itemPlaceHolder" runat="server" />
</div>
</LayoutTemplate>
<ItemTemplate>
<div class="row instructorItem">
<div class="col-2 sessionStartTimeDiv">
<p class="sessionStartTime"><%#Eval("SessionStartTime")%></p>
</div>
<div class="col-2 instructorHeadshotDiv">
<asp:Image class="instructorHeadshot" runat="server" src='<%#Eval("InstructorHeadshot")%>' />
</div>
<div class="col-5 sessionInfoDiv">
<h3 class="instructorName"><%#Eval("InstructorName")%></h3>
<p class="sessionInfo"><%#Eval("SessionInfo")%></p>
</div>
<div class="col-3 checkInBtnDiv">
<asp:Button class="checkInBtn" ID="checkInBtn" runat="server" OnClick="CheckInBtn_Click" Text="Check-In"></asp:Button>
</div>
</div>
<hr />
</ItemTemplate>
<EmptyDataTemplate>
<br />
<br />
No Sessions to Display
</EmptyDataTemplate>
</asp:ListView>
推荐答案
您始终可以将发件人投射回Button.
You can always cast the sender back to a Button.
protected void checkInBtn_Click(object sender, EventArgs e)
{
Button btn = sender as Button;
btn.Text = "New text";
}
您的2个代码段不起作用的原因是因为ListView中的项目基于索引.您将需要执行以下操作.
The reason your 2 snippets don't work is because the items in the ListView are index based. You would need to do something like this.
Button btn = ListView1.Items[i].FindControl("checkInBtn") as Button;
这篇关于代码隐藏功能中的Cant访问按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!