RowCommand未在动态创建的GridView上启动

本文关键字:GridView 启动 创建 动态 RowCommand | 更新日期: 2023-09-27 18:21:48

我正在动态创建一个带有ButtonField和几个BoundFields的网格视图。ButtonField按钮类型为LinkButton。如果我运行它,按钮点击会触发一个post-back,但rowCommand不会被触发。即使我使用AutogenerateSelectButton,它也不会被触发。这一事件具有动力学意义。代码如下:

    protected void B_Search_Click(object sender, EventArgs e) //Search buttonclick that creates and displays the gridview
    {
        gd = getGridView(); //defines the gridview with columns and buttonfield
        gd.DataSource = executeAdvanceSearch(); //retrieves data from DB as Dataset
        gd.DataBind();
        gd.RowCommand += new GridViewCommandEventHandler(gdView_RowCommand); //Rowcommand event binding
        PlaceHolder1.Controls.Add(gd);
    }
    protected void gdView_RowCommand(object sender, GridViewCommandEventArgs e) //not getting triggered on postback
    {
        int index = Convert.ToInt32(e.CommandArgument);
        GridView gdView = (GridView)sender;
        if (e.CommandName == "IDClick")
        {
           //Do something
        }
    }

    private GridView getGridView()
    {
        GridView gdView = new GridView();
        gdView.AutoGenerateColumns = false;
        gdView.AutoGenerateSelectButton = true;
        string name;
        string[] field = ZGP.BLL.Search.getResultFormat(Convert.ToInt32(DDL_ResultView.SelectedValue), out name); //Ignore.  This jst gets columnNames
        if (field.Count() != 0)
        {
            gdView.Columns.Add(getSelectButton()); //Adds linkbutton
            foreach (string cName in field) //ignore. This adds columns.
                if (!String.IsNullOrEmpty(cName))
                {
                    gdView.Columns.Add(GV_DataColumn.getGridViewColumn((DataColumnName)Enum.Parse(typeof(DataColumnName), cName))); //Ignore. adds columns 
                }
        }
        return gdView;
    }
    private ButtonField getSelectButton()
    {
        ButtonField _bf = new ButtonField();
        _bf.ButtonType = ButtonType.Link;
        _bf.HeaderText = "ID";
        _bf.DataTextField = "ID";
        _bf.CommandName = "IDClick";
        return _bf;
    }

谢谢你的帮助。

RowCommand未在动态创建的GridView上启动

if (e.CommandName=="CommandName")
    {
        int index = Convert.ToInt32(e.CommandArgument);
        GridViewRow row = GridView1.Rows[index];
        string boundFieldText= row.Cells[0].Text;
    }

您需要在每次回发时创建网格视图。