Monday, December 10, 2012

Enable/Disable GridView LinkButton Dynamically

First let us create a sample data source for bind to the gridview.

private DataTable createDatatable()

        DataTable dt = new DataTable();
        dt.Columns.Add("Name", typeof(string));
        dt.Columns.Add("Country", typeof(string));
        dt.Columns.Add("URL", typeof(string));
        dt.Columns.Add("Status", typeof(string));

        dt.Rows.Add("Chamara", "Sri lanaka", "", "enable");
        dt.Rows.Add("sam", "America", "", "enable");
        dt.Rows.Add("jhon", "England", "", "disable");
        dt.Rows.Add("cater", "Spain", "", "enable");
        dt.Rows.Add("amanda", "Australia", "", "disable");
        return dt;

What i need is, i wand to add a link button for the URL field and disable it for "jhon" and "amanda". The column "Status" will specify whether the link should be enabled or disabled.

Let create our gridview.

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"

            CellPadding="4" ForeColor="#333333" GridLines="None">
            <AlternatingRowStyle BackColor="White" />
                <asp:BoundField DataField="Name" HeaderText="Name" />
                <asp:BoundField DataField="Country" HeaderText="Country" />
                <asp:TemplateField HeaderText="URL">
                <asp:LinkButton ID="lbURL" runat="server" Text='<%# Eval("URL") %>' Enabled='<%# Eval("Status") != "disable" ? true : false %>'></asp:LinkButton>
            <EditRowStyle BackColor="#2461BF" />
            <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
            <RowStyle BackColor="#EFF3FB" />
            <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
            <SortedAscendingCellStyle BackColor="#F5F7FB" />
            <SortedAscendingHeaderStyle BackColor="#6D95E1" />
            <SortedDescendingCellStyle BackColor="#E9EBEF" />
            <SortedDescendingHeaderStyle BackColor="#4870BE" />

Bind data to the gridview on page load event.

private void BindGrid()
        GridView1.DataSource = createDatatable();

protected void Page_Load(object sender, EventArgs e)
         if (!Page.IsPostBack)

Note the asp:TemplateField in the GridView. In the Enable property of the LinkButton we have used a "if" condition to check the "Status".

No comments:
Write comments
Recommended Posts × +