我有一个文本框,保存在Datalist中。我需要通过ID找到它,这样我就可以将写入该文本框的文本插入到数据库中。这是我的包含文本框的aspx页面。
<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>
带有ID="tb_cmt"
的文本框是我想要在我的代码后面访问的文本框:
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.
}
答案 0 :(得分:4)
您可以使用点击按钮的NamingContainer
property获取DataListItem
。然后,您只需使用FindControl
来获取对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
}