Search code examples
c#asp.netgridviewupdatepanel

ASP.NET - Enabling button by reading data in Grid View inside Update Panel


I have two Buttons and GridView which are:

<asp:Button ID="btn-search" runat="server" OnClick=btn_search_Click />
<asp:Button ID="btn-export" runat="server" OnClick=btn_export_Click />
<asp:GridView ID="gridview1" runat="server" />

btn-search is a control to bind data to the gridview1 from an SqlDataSource. btn-export is disabled at Page_Load and will be enabled when gridview1 has at least one row (btn-export will stay disabled if there is no data/row in gridview1).

At first I wrote this in code behind:

    protected void btn_search_Click(object sender, EventArgs e)
    {
        /* Binding data to GridView */
        if (this.gridview1.Rows.Count > 0)
        {
            this.btn_export.Enabled = true;
        }
    }

and it worked.

But, then I have to wrap the gridview1 in an UpdatePanel so it wont refresh the whole page when data binding in GridView, using btn-search as AsyncPostBackTrigger.

<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:Button ID="btn-search" runat="server" OnClick=btn_search_Click />
<asp:Button ID="btn-export" runat="server" OnClick=btn_export_Click />
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>
        <asp:GridView ID="gridview1" runat="server">
            <Columns>
            </Columns>
        </asp:GridView>
    </ContentTemplate>
<Triggers>
    <asp:AsyncPostBackTrigger ControlID="btn_search" />
</Triggers>
</asp:UpdatePanel>

When the data was bound to gridview1, the btn-search still disabled. I try to write this.btn_export.Enabled = true in GridView and UpdatePanel event such as OnDataBound, OnDataBinding, OnRowDataBound but it still not worked.


Solution

  • Grayfield, it doesnt work because when you click the search button only the update panel content is updated. Try adding the buttons inside the ContentTemplate of the update panel and it should work.