Gridview RowDataBound显示每行的隐藏列

时间:2014-12-15 18:23:35

标签: c# asp.net .net gridview rowdatabound

我有一个gridview,如果选择了某个下拉列表项,我只想允许文本框可编辑。在我的RowDataBound中,我得到了值并决定是否应该编辑它但是.Visible属性不能像我期望的那样工作。使用我的示例数据,我希望第一行和第二行在列中没有文本框,第三行没有文本框,第四行不再使用。任何帮助将不胜感激。

        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        Control ctrl = e.Row.FindControl("ddlPriceTypeCode");

        if (ctrl != null)
        {
            DropDownList ddl = (DropDownList)ctrl;
            if (ddl.SelectedValue == "UPRC-" || ddl.SelectedValue == "PLEV-0" || ddl.SelectedValue == "PLEV-1" || ddl.SelectedValue == "PLEV-2" || ddl.SelectedValue == "PLEV-3" || ddl.SelectedValue == "PLEV-4" || ddl.SelectedValue == "PLEV-5" || ddl.SelectedValue == "PLEV-6" || ddl.SelectedValue == "PLEV-7")
            {
                //GridView1.Columns[4].Visible = true;
            }
            else 
            { 
                //GridView1.Columns[4].Visible = false;
            }
        }
    }

2 个答案:

答案 0 :(得分:2)

以这种方式隐藏/显示整个列。 RowDataBound会触发每一行,因此列的可见性由最后一行的下拉列表的值给出。

如果仅隐藏/显示TextBox,您需要做什么,如下所示:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    Control ctrl = e.Row.FindControl("ddlPriceTypeCode");
    TextBot txt = (TextBox)e.Row.FindControl("txtID");

    if (ctrl != null)
    {
        DropDownList ddl = (DropDownList)ctrl;
        if (ddl.SelectedValue == "UPRC-" || ddl.SelectedValue == "PLEV-0" || ddl.SelectedValue == "PLEV-1" || ddl.SelectedValue == "PLEV-2" || ddl.SelectedValue == "PLEV-3" || ddl.SelectedValue == "PLEV-4" || ddl.SelectedValue == "PLEV-5" || ddl.SelectedValue == "PLEV-6" || ddl.SelectedValue == "PLEV-7")
            txt.Visible = true;
        else 
            txt.Visible = false;
    }
}

显然,“txtID”是您要隐藏/显示的TextBox的ID。

答案 1 :(得分:0)

据我所知,您不会在此事件中检查所选项目。将数据源属性附加到控件时会触发此事件。你应该在selectionChanged事件中检查这个