jeudi 4 mai 2017

Get dynamically created checkbox value from Gridview | Asp.net

I have this gridview where I need to populate more than 25 database tables. These table are lookup table and this gridview is for lookup table maintenance purpose.

Instead of putting specific columns in gridview I directly bind the dataTable to gridview.

This below method assigns the active columns value which is "y"/"n" to checkbox.

<asp:GridView ID="gvTables" runat="server" CssClass="Grid" Width="100%" AutoGenerateColumns="true" Font-Names="Arial"
                                    BorderWidth="1" PagerSettings-Mode="Numeric" Font-Size="8.7pt" Font-Bold="false" AlternatingRowStyle-BackColor="#f4f4f4"
                                    HeaderStyle-BackColor="LightGray" AllowPaging="True" ShowFooter="false" PageSize="12"
                                    OnPageIndexChanging="gvTables_PageIndexChanging"
                                    OnRowDataBound="gvTables_RowDataBound"
                                    OnRowCreated="gvTables_RowCreated"
                                    OnSelectedIndexChanged="gvTables_SelectedIndexChanged">
                                    <PagerStyle CssClass="pgr" />
                                </asp:GridView>

code:

private void SetCheckBoxesInGV()
    {
        ////add checkboxes in place of active
        for (int i = 0; i < gvTables.Rows.Count; i++)
        {
            System.Web.UI.WebControls.CheckBox chk = new System.Web.UI.WebControls.CheckBox();
            chk.ID = "chk";
            chk.Checked = gvTables.Rows[i].Cells[gvTables.Rows[0].Cells.Count - 1].Text.Trim() == "y" ? true : false;
            gvTables.Rows[i].Cells[gvTables.Rows[0].Cells.Count - 1].Controls.Add(chk);
            gvTables.Rows[i].Cells[gvTables.Rows[0].Cells.Count - 1].ControlStyle.CssClass = "ItemCenter";
        }
    }

So the last column looks like this instead of y/n.

enter image description here

Now I want to get the checkbox values, I am using this and thought it will work but it doesn't. Gives null value and "Object reference not set to an instance of an object".

((CheckBox)gvTables.Rows[i].Cells[gvTables.Rows[0].Cells.Count - 1].FindControl("chk")).Checked




Aucun commentaire:

Enregistrer un commentaire