2017-05-07 50 views
0

我試圖訪問labeltextbox的值DataList使用Findcontrol。在運行程序時,我得到的值爲label正確,但從textbox控制中沒有任何值。下面是代碼從datalist findcontrol中得到正確的文本框的值

的.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(); 
     } 

回答

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/>"); 
    } 
} 
相關問題