2017-05-07 2 views
0

labeltextbox의 값을 DataList에 액세스하려고합니다. Findcontrol을 사용하고 있습니다. 프로그램을 실행할 때 label의 올바른 값을 얻었지만 textbox 제어 값은 없습니다. 여기에데이터 목록에서 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/>"); 
    } 
} 
관련 문제