如何在项目命令事件后获取文本框的文本属性

本文关键字:取文本 文本 属性 获取 项目 命令 事件 | 更新日期: 2023-09-27 18:34:38

我在面板内有一个文本框控件,这个面板位于DataList ItemTemplate内。

触发 ItemCommand 事件后,除了 TextBox.Text 属性始终是一个空字符串 " 之外,一切正常,尽管其中有一些文本。

我尝试了几种方法,但没有成功。如果有人能帮助我解决这个问题,我将不胜感激。简化的代码如下所示。谢谢!

ASPX 页:

<asp:DataList ID="dlDataList" runat="server" onitemcommand="dlDataList_ItemCommand">
       <ItemTemplate>
           <asp:Panel ID="pnlReply" runat="server" Visible="False">
             <asp:TextBox ID="txtTextBox" runat="server"></asp:TextBox><br />
             <asp:LinkButton ID="lnkbtnSend" CommandName="Send" runat="server">Send</asp:LinkButton>
           </asp:Panel><br />
           <asp:LinkButton ID="OpenPanel" CommandName="OpenPanel" runat="server">Open panel</asp:LinkButton>
       </ItemTemplate>
</asp:DataList>
</asp:Content>

ASPX.CS页代码隐藏

protected void Page_Load(object sender, EventArgs e)
    {
        FillDataList();
    }
    private void FillDataList()
    {
        List<string> list = new List<string>();
        list.Add("First");
        list.Add("Second");
        list.Add("Third");

        dlDataList.DataSource = list;
        dlDataList.DataBind();
    }
    protected void dlDataList_ItemCommand(object source, DataListCommandEventArgs e)
    {
        if (e.CommandName == "OpenPanel")
        {
            Panel pnlReply = (Panel)e.Item.FindControl("pnlReply");
            pnlReply.Visible = true;
        }
        if (e.CommandName == "Send")
        {
            TextBox txtTextBox = (TextBox)e.Item.FindControl("txtTextBox");
            //I tried this way also..
            //TextBox txtTextBox = (TextBox)e.item.FindControl("pnlReady").FindControl("txtTextBox");
            Label1.Text = txtTextBox.Text;
        }
    }

如何在项目命令事件后获取文本框的文本属性

请在页面加载事件中使用IsPostBack。没有它,您的FillDataList();将在每次回发时执行并重置您的DataList

  protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            FillDataList();
        }
     }