以编程方式单击DataGrid中的ButtonColumn?

时间:2014-05-01 22:23:42

标签: c# asp.net datagrid

我的搜索页面可能会在单独的DataGrid控件中返回多个搜索结果,或者如果搜索足够具体,则会在单个网格中生成单个结果。

如果只找到一个结果,那么我想在该网格的唯一行中调用ButtonColumn的点击,然后打开一个单独的页面,就像用户自己点击它一样。

这是我的Page_LoadComplete事件处理程序:

protected void Page_LoadComplete(object sender, EventArgs e)
{
    var allControls = new List<DataGrid>();

    // Grab a list of all DataGrid controls on the page.
    GetControlList(Page.Controls, allControls);

    var itemsFound = allControls.Sum(childControl => childControl.Items.Count);

    for (var i = 0; i <= allControls.Count; i++)
    {
        itemsFound += allControls[i].Items.Count;

        // If we're at the end of the for loop and only one row has
        // been found, I want to get a reference to the ButtonColumn.
        if (i == allControls.Count && itemsFound == 1)
        {
            var singletonDataGrid = allControls[i];

            // **Here** I want to reference the ButtonColumn and then
            // programmatically click it??


        }            
    }
}

如何获取对相关ButtonColumn的引用,然后以编程方式单击它?

1 个答案:

答案 0 :(得分:0)

找到解决方案。我以编程方式调用OnSelectedIndexChanged事件处理程序(定义为Select_Change),如下所示:

    protected void Page_LoadComplete(object sender, EventArgs e)
    {
        var allControls = new List<DataGrid>();

        // Grab a list of all DataGrid controls.
        GetControlList(Page.Controls, allControls);

        var itemsFound = 
            allControls.Sum(childControl => childControl.Items.Count);

        for (var i = 0; i < allControls.Count; i++)
        {
            if (allControls.Count > 0 && allControls[i].ID == "grid")
            {
                // If a single row is found, grab a reference to the
                // ButtonColumn in the associated grid.
                if (i == (allControls.Count - 1) && itemsFound == 1)
                {
                    var singletonDataGrid = allControls[i];

                    singletonDataGrid.SelectedIndex = 0;

                    Select_Change(singletonDataGrid, new EventArgs());
                }
            }
        }

    }

使用对单行的DataGrid的引用,我还将其SelectedIndex设置为第一行(也是唯一的),以便我可以在调用开始后继续执行其他操作。