从gridview获取值时出错
本文关键字:出错 获取 gridview | 更新日期: 2023-09-27 18:11:57
我有一个GridView,我正在动态绑定网格。在这个网格中,我想使第二个单元格为可编辑的。我能够做到这一点,我修改了文本框后,我将点击提交按钮。这里我的问题是在按钮点击事件,我无法获得文本框的值。
代码<asp:GridView ID="DGridView" runat="server" Font-Size="Small" Width="40%" PageSize="4" ShowHeader="False" OnRowDataBound="DGridView_RowDataBound" AutoPostBack="True" />
protected void DGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
TextBox txtseed = new TextBox();
txtseed.ID = "txtseed";
txtseed.Text = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "seed"));
e.Row.Cells[1].Controls.Add(txtseed);
}
}
protected void butSubmit_Click(object sender, EventArgs e)
{
for (int i = 0; i < DGridView.Rows.Count; i++)
{
strDNo = DGridView.Rows[i].Cells[0].Text;
dty = DGridView.Rows[i].Cells[1].FindControl("txtseed").ToString();
}
}
这里是在dty抛出错误,谁能帮助吗?
在获取文本之前,您需要将对象转换为TextBox。不要忘记设置数据源。你可以按照下面的代码来操作。
public class Test
{
public string Seed { get; set; }
}
protected void Page_Load(object sender, EventArgs e)
{
List<Test> test = new List<Test>();
test.Add(new Test() {Seed = "ssss"});
test.Add(new Test() { Seed = "aaaa" });
DGridView.DataSource = test;
DGridView.DataBind();
}
protected void DGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
TextBox txtseed = new TextBox();
txtseed.ID = "txtseed";
txtseed.Text = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "seed"));
e.Row.Cells[0].Controls.Add(txtseed);
}
}
protected void Button1_OnClick(object sender, EventArgs e)
{
for (int i = 0; i < DGridView.Rows.Count; i++)
{
var strDNo = DGridView.Rows[i].Cells[0].Text;
TextBox dty =(TextBox)DGridView.Rows[i].Cells[0].FindControl("txtseed");
var z = dty.Text;
}
}