【问题标题】:asp:GridView doesn't contain control added in OnRowDataBoundasp:GridView 不包含在 OnRowDataBound 中添加的控件
【发布时间】:2011-05-07 10:11:58
【问题描述】:

我有问题,我无法控制我在 DataGrid 中添加的内容。我将它添加到 OnRowDataBound 事件中,例如:

protected void RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowState == DataControlRowState.Edit || e.Row.RowState == (DataControlRowState.Alternate | DataControlRowState.Edit))
    {
        //int cindex = 0;
        //for (cindex = 0; cindex < e.Row.Controls.Count; cindex++)
        foreach (Control ctl in e.Row.Controls)
        {
            DataControlFieldCell dcctl = (DataControlFieldCell)ctl;
            TableCell tcell = (TableCell)dcctl;

            Label lblComment = new Label();
            TextBox txtComment = new TextBox();

            lblComment.Text = "<br>Comment: ";

            dcctl.Controls.Add(lblComment);
            dcctl.Controls.Add(txtComment);

            //tcell.Controls.Add(lblComment);
            //tcell.Controls.Add(txtComment);

            //e.Row.Cells[cindex].Controls.Add(lblComment);
            //e.Row.Cells[cindex].Controls.Add(txtComment);

这里发生了什么:默认情况下,TableCell 中已经存在一个 TextBox,我想再添加一个 TextBox 和 Label。边界后我可以看到 2 个文本框,我可以在两者中输入数据,但是当我单击更新按钮时,会引发 OnRowUpdating 事件,我无法获取我的文本框!

protected void RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        grdView.EditIndex = -1;
        int counter = 0;

        for (counter = 0; counter < grdView.Rows[e.RowIndex].Cells.Count; counter++)
        {
            foreach (Control ctl in grdView.Rows[e.RowIndex].Cells[counter].Controls)
            {

在这里,我将只获得一个默认的 TextBox(及其值)。但是我的文本框消失了! :(

你能建议我在这里做什么?

附:我不能在 aspx 文件中使用预定义列,例如 asp:TemplateField,因为我的表每次都有不同数量的行。它是动态的

【问题讨论】:

    标签: asp.net gridview


    【解决方案1】:

    问题在于,在您将控件动态添加到页面(或页面的任何子控件,例如数据网格)之后,您必须在回发时在服务器端重新创建控件。如果您不在服务器端重新创建控件,那么当运行时处理回发时,它将不知道将表单发布的内容放在哪里。

    所以本质上,当页面处理回发时,它会看到一个名为“gridView1_txtComment”的 HTML 字段(我知道,实际的 HTML id 可能是别的东西)。但是服务器端代码模型只有一个 gridView1 的实例,没有一个名为 txtComment 的 TextBox 实例除非您运行RowDataBound 方法再次来创建它控制。

    【讨论】:

    • 我应该如何再次运行 RowDataBound? lz能否描述的更详细些?
    • 您可能需要重新调整添加这些控件的方式。我不能给你一个好的(简单的)例子,因为这个问题有点复杂。您必须了解的要点是:在回发时,您负责重新创建任何动态创建的控件,以便回发处理程序可以用回发结果填充它们。
    【解决方案2】:

    我认为这与 ViewState 有关。从中创建一个模板列,然后将第二个文本框添加到模板中。

    【讨论】:

      【解决方案3】:

      我做到了!

      拒绝在 OnRowDataBound 中动态添加控件,并创建动态 TempalteField 列,其中包含我需要的 2 个 TextBoxes 和 Label。 (在http://www.codeproject.com/KB/aspnet/create_template_columns.aspx的帮助下)

      但是在我的问题又回来了.. OnRowUpdating 事件仍然没有我添加的文本框。最后我发现这里有通知http://forums.asp.net/p/1537632/3738331.aspx,需要在Page_Load上实现TempalteField-s添加,帮助我解决了问题!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-06-29
        • 1970-01-01
        • 1970-01-01
        • 2016-02-19
        • 2013-12-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多