我有一个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是抛出错误,有人可以帮忙吗?
答案 0 :(得分:0)
在获取文本之前,您需要将对象转换为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;
}
}