Access TextBox in DataList by ID from Button-Click

2020-04-17 05:55发布

问题:

I have a textbox which is kept inside Datalist. I need to find it via ID, so that i can insert text written to that textbox to the database.Here is my aspx page containing textbox.

<asp:Content ID="Content1" ContentPlaceHolderID="ccont" Runat="Server">
  <div id="ccont">
      <asp:DataList ID="mydatalist" ItemStyle-CssClass="lft_c_down"  runat="server">
        <ItemTemplate>
          <div id="wholeC">
            <div id="ctop">
             <div id="lft_l">
                <div id="lft_c_top">
                   <asp:Image runat="server" ImageUrl='<%#DataBinder.Eval(Container.DataItem,"ipath")%>' Height="250px" Width="300px" />
                    <br/>
                </div>
                <div id="lft_c_down">
                   <b>Product Name:</b>
                   <asp:Label ID="lbl2" Text='<%#DataBinder.Eval(Container.DataItem,"products") %>' runat="server" />
                   <br/>
                   <b>brand:</b>
                   <asp:Label ID="lbl1" Text='<%#DataBinder.Eval(Container.DataItem,"brand") %>' runat="server" />
                   <br/>
                   <b>Price:</b>
                   <asp:Label ID="Label1" Text='<%#DataBinder.Eval(Container.DataItem,"price") %>' runat="server" />
                </div>
              </div>
              <div id="lft_r">
                    <b>Details:</b>
                   <asp:Label ID="Label2" Text='<%#DataBinder.Eval(Container.DataItem,"description") %>' runat="server" />
              </div>
           </div>
          <div id="cmt">
               <asp:TextBox ID="tb_cmt" runat="server" Height="35px" Width="620" placeholder="comment.."  />
               <asp:Button ID="Button1" runat="server" Text="Comment" backcolor="black" BorderStyle="None" Font-Names="Consolas" Font-Overline="False" 
                ForeColor="White" Height="34px" Width="108px" OnClick="cmt_Click" />
           </div>
         </div>
        </ItemTemplate>
      </asp:DataList>

       </div>

The Textbox with ID="tb_cmt" is the text box i want to access in my code behind as:

protected void cmt_Click(object sender, EventArgs e)
{
    // how to get the TextBox?
    sq.connection();
    SqlCommand cmd = new SqlCommand("insert into comment(ecomment,sid) values(@myecomment,@mysid)", sq.con);
    cmd.Parameters.AddWithValue("@myecomment",tb_cmt.text)//but here tb_cmt is not recognized.
}

回答1:

You can use the NamingContainer property of the button that was clicked to get the DataListItem. Then you just have to use FindControl to get the reference to your TextBox:

protected void cmt_Click(object sender, EventArgs e)
{
    Button btn = (Button) sender;
    DataListItem item = (DataListItem) btn.NamingContainer;
    TextBox txt = (TextBox) item.FindControl("tb_cmt");
    //... save
}