【问题标题】:Not getting correct value of textbox from findcontrol from datalist没有从 datalist 中的 findcontrol 获取正确的文本框值
【发布时间】:2017-10-05 16:34:00
【问题描述】:

我正在尝试使用Findcontrol 访问DataList 内的label 和textbox 的值。在运行程序时,我得到了正确的label 值,但没有来自textbox 控件的值。这是代码

.aspx 代码

<asp:DataList ID="SubjectAdded" runat="server">
    <ItemTemplate>
        <table>
            <tr>
                <td>
                    <asp:Label ID="SubjectLbl" runat="server" Text='<%# Eval("subject") %>'</asp:Label> 
                </td>
                <td>
                    <asp:TextBox ID="FeeBox" runat="server"></asp:TextBox>
                </td>
             </tr>
         </table>
     </ItemTemplate>
</asp:DataList>

.aspx.cs 代码

 for(int i=0; i<SubjectAdded.Items.Count; i++)
        {
            string feeTB = ((TextBox)SubjectAdded.Items[i].FindControl("FeeBox")).Text;
            string subjectNameLb = ((Label)SubjectAdded.Items[i].FindControl("SubjectLbl")).Text ;

            string str = "UPDATE table name SET FEE='" + feeTB + "' WHERE TUTOR = '" + id+ "' AND SUBJECT = '" + subjectNameLb + "'";
            SqlCommand strCmd = new SqlCommand(str, con);
            con.Open();
            strCmd.ExecuteNonQuery();
            con.Close();
        }

【问题讨论】:

    标签: c# asp.net datalist findcontrol


    【解决方案1】:

    这段代码对我有用,也许你错过了IsPostback?:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            SubjectAdded.DataSource = new[] {
                new {Id= 1, Subject = "Text 1"  },
                new {Id= 2, Subject = "Text 2"  },
            };
            SubjectAdded.DataBind();
        }
    }
    
    public void Page_PreRender(object sender, EventArgs e)
    {
        for (int i = 0; i < SubjectAdded.Items.Count; i++)
        {
            string feeTB = ((TextBox)SubjectAdded.Items[i].FindControl("FeeBox")).Text;
            string subjectNameLb = ((Label)SubjectAdded.Items[i].FindControl("SubjectLbl")).Text;
    
            Response.Write($"{subjectNameLb}: {feeTB}<br/>");
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-29
      • 1970-01-01
      • 2022-08-16
      • 1970-01-01
      • 2015-08-16
      相关资源
      最近更新 更多