我有一个ASP.NET DataList
,页脚定义如下:
<FooterTemplate>
<asp:DropDownList ID="ddlStatusList" runat="server">
</asp:DropDownList>
<input id="txtNotes" type="text" placeholder="Notes" />
<asp:Button runat="server" type="button" Text="Add" ID="btnAdd"></asp:Button>
</FooterTemplate>
我想做的是,单击btnAdd
,从txtNotes
和ddlStatusList
中获取值,但我不知道如何访问控件,更不用说值了。
我不能执行这样的操作,因为我将无法检查我的按钮是否已被单击(使用复选框也是可能的),即使这样,我也不确定我是否能够像演示的那样使用findControl
。(DataList
的页脚与项目的行为是否不同?)
我不能使用Button
的commandName
&commandValue
属性,因为在数据绑定时,输入的文本将不存在,因此我无法设置CommandValue
。
我尝试使用LinkButton
而不是普通的.NET Button
,但遇到了同样的问题,因此我无法计算如何从TextBox
/DropDownList
中获取值
以下内容应该有效。参见我添加的runat="Server"以获取txt注释:
aspx:
<FooterTemplate>
<asp:DropDownList ID="ddlStatusList" runat="server">
</asp:DropDownList>
<input id="txtNotes" runat="server" type="text" placeholder="Notes" />
<asp:Button runat="server" type="button" Text="Add" ID="btnAdd"></asp:Button>
</FooterTemplate>
C#:
protected void btnAdd_Click(object sender, EventArgs e)
{
var txtNotes = (System.Web.UI.HtmlControls.HtmlInputText)(((Button)sender).Parent).FindControl("txtNotes");
var ddlStatusList = (DropDownList)(((Button)sender).Parent).FindControl("ddlStatusList");
}
您可以使用Control.NamingContainer访问一行中的其他控件:
<FooterTemplate>
<asp:DropDownList ID="ddlStatusList" runat="server">
</asp:DropDownList>
<input id="txtNotes" type="text" placeholder="Notes" runat="server" />
<asp:Button runat="server" type="button" Text="Add" ID="btnAdd" OnClick="btnAdd_Click"></asp:Button>
</FooterTemplate>
protected void btnAdd_Click(object sender, EventArgs e)
{
Button btnAdd = (Button)sender;
DropDownList ddlStatusList = (DropDownList)btnAdd.NamingContainer.FindControl("ddlStatusList");
System.Web.UI.HtmlControls.HtmlInputText txtNotes = (System.Web.UI.HtmlControls.HtmlInputText)btnAdd.NamingContainer.FindControl("txtNotes");
int index = ddlStatusList.SelectedIndex;
string text = txtNotes.Value;
}