如何在C#中将LiteralControl转换为LinkBut​​ton

时间:2015-03-10 20:42:56

标签: c# asp.net

protected void gvDispMsg_RowCreated(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.Header)
    {
        GridView hGrid = (GridView)sender;
        GridViewRow gvrRow = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Insert);

        TableHeaderCell tcCellSub1 = new TableHeaderCell();
        tcCellSub1.Controls.Add(lblDDLBlank);
        gvrRow.Cells.Add(tcCellSub1);

        gvDispMsg.Controls[0].Controls.AddAt(0, gvrRow);

        LinkButton btnSort;
        System.Web.UI.WebControls.Image image;
        //iterate through all the header cells
        foreach (TableCell cell in e.Row.Cells)
        {
            //check if the header cell has any child controls
            if (cell.HasControls())
            {
                //get reference to the button column
                btnSort = (LinkButton)cell.Controls[0];
                image = new System.Web.UI.WebControls.Image();
                if (ViewState["sortExp"] != null)
                {
                    //Do something
                }
            }
        }
    }
}

我在第btnSort = (LinkButton)cell.Controls[0];行中收到以下错误:

Unable to cast object of type 'System.Web.UI.LiteralControl' to type 'System.Web.UI.WebControls.LinkButton'.

如何解决错误。

1 个答案:

答案 0 :(得分:1)

我知道这是一个老问题,但如果将来有人在搜索中找到它,这是从网格视图中投射链接按钮的正确方法:

var btnSort = (LinkButton)GridView1.Rows[i].Cells[k].Controls[1];