Disabling a LinkButton within a GridViewclick using JavaScript on the Client Side

I am working with a GridView that includes a LinkButton control in one of the columns. I need to disable the click event from the client side based on certain conditions for this column. This means that for some rows, users should not be able to trigger the onclick event, while for others it should be allowed. I would like to implement this functionality using JavaScript. Additionally, when a user clicks on the link, they should receive a notification indicating that the action cannot be completed for that particular row.

<asp:GridView Width="100%" ShowHeader="true" ViewStateMode="Enabled" GridLines="Both" CellPadding="10" CellSpacing="5" ID="GridViewMultiplePOSAssociationId" runat="server" AllowSorting="false" AutoGenerateColumns="false" OnRowCommand="RewardGridMultiD_RowCommand"
AllowPaging="true" PageSize="8" OnRowDataBound="grdViewCustomers_OnRowDataBound" PagerSettings-Position="Top" PagerSettings-Mode="NumericFirstLast" PagerSettings-FirstPageText="First" PagerSettings-LastPageText="Last" DataKeyNames="POS Id">
    <RowStyle CssClass="table_inner_text" BackColor="WhiteSmoke" BorderColor="CornflowerBlue" Wrap="true" ForeColor="Black" Height="30px" />
    <HeaderStyle CssClass="table_head_text" />
    <Columns>
        <asp:TemplateField ItemStyle-Width="80px">
            <ItemTemplate>
                <a href="JavaScript:divexpandcollapse('div<%# Eval(" POS Id ") %>');">
                    <img alt="Details" id="imgdiv<%# Eval("POS Id") %>" src="images/plus.png" />
                </a>
                <div id="div<%# Eval(" POS Id ") %>" style="display: none;">
                    <asp:GridView ID="grdViewOrdersOfCustomer" runat="server" AutoGenerateColumns="false" CssClass="ChildGrid">
                        <RowStyle CssClass="table_inner_text" BackColor="SkyBlue" BorderColor="Black" Wrap="true" ForeColor="White" Height="30px" />
                        <Columns>
                            <asp:BoundField ItemStyle-Width="150px" DataField="RULE FILE NAME" HeaderText="RULE FILE NAME" />
                            <asp:BoundField ItemStyle-Width="150px" DataField="RULE ID" HeaderText="RULE ID" />
                            <asp:BoundField ItemStyle-Width="150px" DataField="RULE TYPE ID" HeaderText="RULE TYPE ID" />
                            <asp:BoundField ItemStyle-Width="150px" DataField="START TIME" HeaderText="START TIME" />
                            <asp:BoundField ItemStyle-Width="150px" DataField="EXPIRY TIME" HeaderText="EXPIRY TIME" />
                        </Columns>
                    </asp:GridView>
                </div>
            </ItemTemplate>
        </asp:TemplateField>

        <asp:TemplateField HeaderStyle-Width="80px" ItemStyle-Width="80px" ItemStyle-HorizontalAlign="Center" HeaderText="Row Number">
            <ItemTemplate>
                <asp:Label ID="LabelRowNumberId" runat="server" Text='<%#Eval("Row Number") %>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderStyle-Width="80px" ItemStyle-Width="80px" ItemStyle-HorizontalAlign="Center" HeaderText="POS Id">
            <ItemTemplate>
                <asp:Label ID="LabelPOSID" runat="server" Text='<%#Eval("POS Id") %>'></asp:Label>
                <%-- <asp:LinkButton ID="LinkbtnPOSId" CommandArgument='<%#Eval("POS Id") %>' CommandName="ClickPOS" Text='<%#Eval("POS Id") %>' runat="server" CausesValidation="false"></asp:LinkButton>--%>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderStyle-Width="80px" ItemStyle-Width="250px" ItemStyle-HorizontalAlign="Center" HeaderText="Action">
            <ItemTemplate>
                <asp:LinkButton ID="HyperLinkAssociate" CommandArgument='<%#Eval("POS Id") %>' CommandName="Associate" Text="Associate" runat="server" OnClientClick="return OnClientClickAssociateRewardRuleFile(this);" CausesValidation="false"></asp:LinkButton>/
                <asp:LinkButton ID="HyperLinkReplace" CommandArgument='<%#Eval("POS Id") %>' CommandName="Replace" Text="Replace" runat="server" OnClientClick="return OnClientClickReplaceRewardRuleFile(this);" CausesValidation="false"></asp:LinkButton>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderStyle-Width="80px" ItemStyle-Width="250px" ItemStyle-HorizontalAlign="Center" HeaderText="Status">
            <ItemTemplate>
                <asp:Label runat="server" ID="LabelStatusPendingPOSId" Text='<%#Eval("Status") %>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

Within the GridViewMultiplePOSAssociationId, there is a column labeled "Status" which contains a label named LabelStatusPendingPOSId. The text of LabelStatusPendingPOSId is dynamically set as either "Applied" or "Not Applied" during binding. If the status is "Applied", users should not be able to click on the Associate/Replace LinkButtons, otherwise, they are allowed to do so.

Answer №1

implement the OnRowDataBound code to enhance your Grid functionality

 protected void grdViewCustomers_OnRowDataBound(object sender, GridViewRowEventArgs e)
    { 
        if (e.Row.RowType==DataControlRowType.DataRow)
    {
    LinkButton LinkbtnPOSId=(LinkButton)e.Row.FindControl("LinkbtnPOSId");
    Label LabelStatusPendingPOSId = (Label)e.Row.FindControl("LabelStatusPendingPOSId");
    Boolean boolStatus = LabelStatusPendingPOSId.Text == "Applied" ? true : false;
    //LinkbtnPOSId.Attributes.Add("onclick", "function CheckStatus('" + boolStatus.ToString() + "')");   
    LinkbtnPOSId.Enabled = boolStatus;

    }

    }

Answer №2

Check out this solution...

If you want to disable specific controls within a Gridview element, you can achieve that by looping through them in the Javascript pageload function...

Here is an example of how you can implement this:

function PageLoad(sender, args) 
{
    for (var i = 0; i <= RowCount; i++) 
    {
        document.getElementById('Gridview1_HyperLinkAssociate_' + i.toString() + '').disabled = true;
    }
}

Make sure to adjust the value of RowCount to match the number of rows in your Gridview...

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using a for loop, how can the property value be set in another object?

One challenge that I am facing is setting object property values. The object in question looks like this: const newPlan = { name: '', description: '', number: '', monday: { breakfast: '', ...

Tips for saving and retrieving req.user using JsonwebToken

Looking for ways to store and retrieve req.user using JsonwebToken in my booking application built with Node. I need to fetch the user information who booked a product and display it on the admin portal. .then((user) => { const maxAge = 3 * 60 * ...

Display an image when the cursor hovers over a text

I'm attempting to display an image when hovering over specific text. The image should not replace the text, but appear in a different location. The concept is as follows: When hovering over the word "Google", the Google logo should appear in the red ...

Adding Jquery to Codeigniter version 2.X

I've been trying to incorporate Jquery into my codeigniter 2.X project without success. I added the library link and confirmed in the debugger that it loads without any errors. However, when I try to use the Document ready function, it simply doesn&ap ...

Storing user input as an object key in typescript: A comprehensive guide

When delving into Firestore for the first time, I quickly learned that the recommended modeling approach looks something like this: check out the model here members { id: xyz { name: Jones; ...

Error encountered: SQLITE_BUSY - Unable to access the database due to it being locked. This

router.post("/update-quiz", upload.single("file"), async (req, res) => { const transaction = await sequelize.transaction(); try { const actions = { "Multiple Choice": async (questions, transacti ...

Modify the parent div's background color on mouseover of the child li

I want to update the background image of a parent div that contains a series of ul li elements. Here is the HTML code I am working with: <section class="list" id="services"> <div class="row"> <ul> <li>& ...

Converting a string to a date type within a dynamically generated mat-table

I am working on a mat-table that shows columns for Date, Before Time Period, and After Time Period. Here is the HTML code for it: <ng-container matColumnDef="{{ column }}" *ngFor="let column of columnsToDisplay" > ...

CSS trick for masking line borders with parent corner radius

I'm currently utilizing next js for my web application, and I have encountered a specific requirement that needs addressing. You can find the visual representation of this requirement in the following image: https://i.sstatic.net/zGVrl.png The progr ...

Is the data missing in the initial request?

After creating a function that returns an object with mapped values, I encountered an issue. The second map is undefined the first time it runs, causing my vue.js component to display data from the first map but not the cutOff value. Strangely, when I re ...

Can you provide guidance on how to pass the selected value from a select option to an onchange function using Vue.js methods?

I'm facing an issue with passing the selected option value id from a select option to an onchange function in my methods. My goal is to store the selected value in the v-model "choosed" every time the user changes the select option, and then pass that ...

Obtain specific fields from a multidimensional array object using lodash

My dilemma involves working with an object that has the following structure: var data = [ { "inputDate":"2017-11-25T00:00:00.000Z", "billingCycle":6, "total":1 },{ "inputDate":"2017-11-28T00:00:00.000Z", "bi ...

Setting the NameClaimType for an ASP.Net MVC 5 website: A step-by-step guide

I have developed a website using ASP.Net MVC 5 with Microsoft's "On-Premises" Organization Account Authentication mechanism, which is linked to my company's ADFS infrastructure. While I am receiving all the configured claims, the ClaimsIdentity.N ...

Setting default values for Vue prop of type "Object"

When setting default values for objects or arrays in Vue components, it is recommended to use a factory function (source). For example: foobar: { type: Object, default() { return {} } } // OR foobar: { type: Object, default: () => ({}) ...

Error: The page "..." contains an invalid "default" export. The type "..." is not recognized in Next.js

Currently, I have a functional component set up for the Signup page. My goal is to define props within this component so that I can pass the necessary values to it from another component. This is my current approach: export default function SignupPage({mod ...

When I specify the type for the function parameter, an error occurs when I attempt to execute the function

When I assign a generic type to the function parameter and try to call the function, an error message pops up stating "This expression is not callable. Type unknown has no call signature." function a() { return 'abc' } function fun<T>(x: T ...

Learn the process of extracting various data from a PHP source and saving it in select options through AJAX

One of the features on my website is a select option that allows users to choose a hotel name obtained from a dynamic php script. Once a hotel is selected, another select option displays room types available based on the chosen hotel. However, there seem ...

Combining an anchor tag in HTML with PHP

I have attempted: <?php include("delete.php") ?> <?php .... .... .... if($result=mysql_query($sql)) { echo "<table><th>Id</th><th>Name</th><th>Description</th ...

Next.js Static Paths Filtering

How can I retrieve only filtered paths from getStaticPaths? This function currently returns all posts export async function getStaticPaths() { const { data } = await axios.get(`${url}/category`, config); const paths = data.map((post) => { ...

Applying a class to a parent element in a React component

I am working on a React component that consists of two buttons. My goal is to dynamically set a class on the container div based on which button is clicked... Component (AddOn) js import React, { useState } from 'react'; function AddOns(props ...