Search code examples
c#asp.net.netgridviewrowdatabound

Gridview RowDataBound show hide column for each row


I have a gridview where I only want to allow a textbox to be editable if a certain drop down list item is selected. In my RowDataBound, I get the value and decide if it should be edited but the .Visible attribute is not working as I expect it to. Using my sample data, I would expect the first and second row to NOT have a textbox in the column, the third to have a textbox, and the fourth NOT to again. Any help would be greatly appreciated.

        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;
            }
        }
    }

Solution

  • In this way your hiding/showing the entire column. The RowDataBound fires for every rows, so the visibility of the column is given by the value of the dropdownlist of the last row.

    What you have to do if hide/show the TextBox only, like this:

    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;
        }
    }
    

    Where, obviously, "txtID" is the ID of the TextBox you want to hide/show.