asp.netgridviewcheckboxeditautogeneratecolumn

Gridview, Autogenerated Column, Checkbox Column Editable


I have a gridview binded to a datasource.

 <asp:GridView ID="DocumentReviewGrid" runat="server" AllowPaging="True" AllowSorting="True"
                    EnableModelValidation="True" Width="100%" BorderStyle="None" 
                    CssClass="docnav_data" BorderWidth="1px" GridLines="None" DataSourceID="DocumentReviewDataSource"
                    HorizontalAlign="Left" OnRowDataBound="DocumentReviewGrid_RowDataBound" 
                    OnRowCreated="DocumentReviewGrid_RowCreated" CellSpacing="5"
                    PageSize="20" OnPageIndexChanged="DocumentReviewGrid_PageIndexChanged">
                    <AlternatingRowStyle BackColor="#EBF2F9" BorderStyle="None" />
                    <FooterStyle HorizontalAlign="Left" />
                    <HeaderStyle BackColor="#E7E7E7" HorizontalAlign="Left" />
                    <PagerSettings Mode="NumericFirstLast" Position="Top" PageButtonCount="4" />
                    <PagerStyle HorizontalAlign="Center" />                       
                </asp:GridView>

enter image description here

As you can see Autogenerated Column is set to true, and it must be kept like that. One of the column is a SQL bit value, so it's represented as checkbox. I would like to be able to edit the checkbox column only, without using "AutoGenerateEditButton" property. I would just like to:


Solution

  • Autogenerated columns cannot be manipulated directly in pretty much anyway, so there is no simple way to do it. So what you could do is create a custom column, which will always come first before any auto generated columns (again, this behavior cannot be changed), and hide the auto generated bit column.

    How to hide the column is described here. Essentially you cannot use Columns collection, so need to do this:

    protected void DocumentReviewGrid_RowCreated(object sender, GridViewRowEventArgs e)
    {
        e.Row.Cells[X].Visible = false; // hides the first column
    }
    

    Here X is the 0-based index of the column to hide.

    And now to prepend the column just define it the way you want, leaving AutoGenerateColumns="true":

    <asp:GridView ID="DocumentReviewGrid"...>
        <Columns>
            <asp:CheckBoxField HeaderText="Esclusione" DataField="Esclusione" />
        </Columns>
    </asp:GridView>
    

    Admittedly this is quite hackish, but that will get you almost where you want - bool column displayed and editable.