2017-05-07 162 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/>"); 
    } 
} 
相关问题