通過使用FindControl搜索正確的行,可以訪問GridView中的所有控件。爲此,您可以將行號作爲CommandArgument發送,並在後面的代碼中使用。因此,首先使用OnCommand
代替OnClick
,並在aspx頁面上設置CommandArgument
。
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Purchase" OnCommand="Button1_Command" CommandArgument='<%# Container.DataItemIndex %>' />
</ItemTemplate>
</asp:TemplateField>
然後在後面
代碼
protected void Button1_Command(object sender, CommandEventArgs e)
{
//get the rownumber from the command argument
int rowIndex = Convert.ToInt32(e.CommandArgument);
//find the textbox in the corrext row with findcontrol
TextBox tb = GridView1.Rows[rowIndex].FindControl("TextBox1") as TextBox;
//get the value from the textbox
try
{
int numberOfTickets = Convert.ToInt32(tb.Text);
}
catch
{
//textbox is empty or not a number
}
}