我正在尝试检索输入到Gridview文本框中的数据,但是我没有从中获取数据。这是我的代码:
ASP中的
<asp:GridView ID="Add" runat="server">
<Columns>
<asp:TemplateField HeaderText="Select" HeaderStyle-Width="100px">
<ItemTemplate>
<asp:CheckBox ID="cbox_Select" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField = "Name" HeaderText = "Fee Type" />
<asp:TemplateField HeaderText="Amount" HeaderStyle-Width="100px">
<ItemTemplate>
<asp:TextBox ID="TextBox" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
和C#,
for (int i = 0; i< n;i++)
{
string a = ((TextBox)Add.Rows[i].Cells[2].FindControl("TextBox")).Text;
}
任何人都可以帮我吗?
答案 0 :(得分:5)
您希望循环浏览GridViewRowCollection,然后找到控件。
foreach (GridViewRow row in Add.Rows)
{
var textbox = row.FindControl("TextBox") as TextBox;
var a = textbox.Text;
}
<asp:Button ID="Button1" runat="server" Text="SubmitButton"
OnClick="SubmitButton_Click" />
<asp:GridView ID="Add" runat="server">
<Columns>
<asp:TemplateField HeaderText="Amount" HeaderStyle-Width="100px">
<ItemTemplate>
<asp:TextBox ID="TextBox" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
public class SampleClass
{
public int Id { get; set; }
public string Text { get; set; }
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Add.DataSource = new List<SampleClass>()
{
new SampleClass {Id = 1, Text = "One"},
new SampleClass {Id = 2, Text = "Two"},
};
Add.DataBind();
}
}
protected void SubmitButton_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in Add.Rows)
{
var textbox = row.FindControl("TextBox") as TextBox;
var a = textbox.Text;
}
}
答案 1 :(得分:2)
您收到错误了吗?
尝试在For循环中包含一个条件...
If(row.RowType == row.DataControlRowType.DataRow) {
//do something
}