Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get selected Row in a pop up for Edit and Update

I have a anchor tag for the updating the row in the gridview. I have set the checkbox in the gridview. When the user checks the checkbox and click on update button the existing row should open in a pop up..

Right now the pop up is opening but not with the checked rows with the existing data. Please see the code for your reference:-

<a id="popup" onclick="div_show()" class="btn btn-success"><i class="fa fa-plus-circle"></i>Add new</a>

<a href="javascript:;" class="btn btn-primary" runat="server" onclick="div_show()" ><i class="fa fa-refresh"></i>Update</a>

Also see the gridview code for your reference:-

<asp:GridView ID="grdCSRPageData" runat="server" Width="100%" border="1" Style="border: 1px solid #E5E5E5;" CellPadding="3"
            AutoGenerateColumns="False" OnDataBound="grdCSRPageData_DataBound" AllowPaging="true" CssClass="hoverTable" EmptyDataText="No Records Found"
            OnPageIndexChanging="grdCSRPageData_PageIndexChanging" DataKeyNames="Id" OnRowDeleting="grdCSRPageData_RowDeleting"
            PageSize="5" ShowFooter="true" OnRowEditing="grdCSRPageData_RowEditing" OnRowUpdating="grdCSRPageData_RowUpdating"
            OnRowCancelingEdit="grdCSRPageData_RowCancelingEdit">
            <AlternatingRowStyle CssClass="k-alt" BackColor="#f5f5f5" />
            <Columns>
                <asp:TemplateField HeaderText="Select" HeaderStyle-Width="5%" HeaderStyle-CssClass="k-grid td">
                    <ItemTemplate>
                        <asp:CheckBox ID="chkSelect" runat="server" AutoPostBack="false" />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:BoundField DataField="page_title" HeaderText="Page Title" ItemStyle-Width="30" HeaderStyle-CssClass="k-grid td" />
                <asp:BoundField DataField="page_description" HeaderText="Page Description" ItemStyle-Width="30" HeaderStyle-CssClass="k-grid td" />
                <asp:BoundField DataField="meta_title" HeaderText="Meta Title" ItemStyle-Width="30" HeaderStyle-CssClass="k-grid td" />
                <asp:BoundField DataField="meta_keywords" HeaderText="Meta Keywords" ItemStyle-Width="30" HeaderStyle-CssClass="k-grid td" />
                <asp:BoundField DataField="meta_description" HeaderText="Meta Description" ItemStyle-Width="30" HeaderStyle-CssClass="k-grid td" />
                <asp:BoundField DataField="Active" HeaderText="Active" ItemStyle-Width="30" HeaderStyle-CssClass="k-grid td" />
                <asp:TemplateField HeaderText="Action" HeaderStyle-Width="15%" HeaderStyle-CssClass="k-grid td">
                    <ItemTemplate>
                        <asp:ImageButton ID="btnDelete" AlternateText="Delete" ImageUrl="~/images/delete.png" runat="server" Width="15" Height="15" CommandName="Delete" CommandArgument='<%# Eval("Id") %>' CausesValidation="false" OnClientClick="return confirm('Are you sure you want to delete this record?')" />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:CommandField ButtonType="Image" ItemStyle-Width="15" EditImageUrl="~/images/edit.png" ShowEditButton="True" ControlStyle-Width="15" ControlStyle-Height="15" CancelImageUrl="~/images/close.png" UpdateImageUrl="~/images/update.png">
                    <ControlStyle Height="20px" Width="20px"></ControlStyle>
                </asp:CommandField>
            </Columns>
        </asp:GridView>

Please help, its been since two days I am stucked but couldn't cracked it.

Code for binding the gridview:-

private void BindGrid()
    {
        string strQuery = "select Id,page_title,page_description,meta_title,meta_keywords,meta_description,Active from tbl_Pages ORDER By Id DESC";
        SqlCommand cmd = new SqlCommand(strQuery);
        DataTable dt = GetData(cmd);
        grdCSRPageData.DataSource = dt;
        grdCSRPageData.DataBind();
    }

Also see the Page_load method;-

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {  
            BindGrid();
        }
    }
like image 486
Rahul Sutar Avatar asked Dec 11 '14 15:12

Rahul Sutar


2 Answers

You can try this using the AjaxControlToolKit.

In your GridView place this event handler:

OnRowCommand="grdCSRPageData_RowCommand"

Place this after your GridView:

<asp:UpdatePanel ID="upModal" runat="server" UpdateMode="Conditional">
    <ContentTemplate>
        <asp:Panel ID="pnlModal" runat="server" BorderWidth="1" Style="display:none;">
            <table>
                <tr>
                    <td>page_title</td>
                    <td><asp:TextBox ID="txtPageTitle" runat="server" /></td>
                </tr>
                <tr>
                    <td>page_description</td>
                    <td><asp:TextBox ID="txtPageDescription" runat="server" /></td>
                </tr>
            </table>
            <asp:Button ID="btnOK" runat="server" Text="OK" />
            <asp:Button ID="btnCancel" runat="server" Text="Cancel" />
        </asp:Panel>
    </ContentTemplate>
</asp:UpdatePanel>
<asp:Button ID="btnModal" runat="server" Style="display:none;"/>
<ajaxToolkit:ModalPopupExtender ID="mpe" runat="server" PopupControlID="pnlModal" TargetControlID="btnModal" OkControlID="btnOK" CancelControlID="btnCancel" />

In code behind:

protected void grdCSRPageData_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName == "Edit")
    {
        GridViewRow gvRow = grdCSRPageData.Rows[Convert.ToInt32(e.CommandArgument)];
        txtPageTitle.Text = gvRow.Cells[0].Text;
        txtPageDescription.Text = gvRow.Cells[1].Text;

        upModal.Update();
        mpe.Show();
    }
}

protected void grdCSRPageData_RowEditing(object sender, GridViewEditEventArgs e)
{
    grdCSRPageData.EditIndex = -1;
    BindGrid();
}

I think you don't need to check which row you want to edit, you already have a CommandField in your GridView. You just click on the edit image and the modal popup gets populated with the data from the GridView (from the row you are editing).

like image 109
dario Avatar answered Nov 12 '22 11:11

dario


Here is a solution using ajax. When you check a checkbox and click on update button jquery code will look for selected checkbox in gridview and when it finds this will assign values to textboxes which will be in popup.

Also you have to store id in hidden field on the basis of which update query will run or you can use any field on which update will happen.

Now when you click on update button in popup an ajax call will be sent which will take updated values from textboxes and send to webmethod.

In webmethod you will run your update query.And when ajax executes successfully you will empty the values of textboxes in popup and reload the page to see changes in gridview.

Html of popup

<div id="Popup">
    <table>
        <tr>
            <td>
                Category
            </td>
            <td>
                <input type="text" id="Category" />
            </td>

        </tr>
        <tr>
            <td>
                Items
            </td>
            <td>
                <input type="text" id="items" />
            </td>
        </tr>
        <tr>
            <td>
                <input type="button" value="Update" onclick="Openselected()" />
            </td>
            <td><input type="hidden" id="hdnID" /></td>
        </tr>

    </table>
</div>

This is not shown as popup but you can use any plugin to show it in popup like blockui,fancybox jqueryui dialog or any one available.

Jquery Code

This function will assign values of selected row in textboxes and open popup.

function Openselected()
    {
        $('table[id$=grdTest] tr').each(function () {

            if ($(this).find('input[type=checkbox]').is(':checked')) {
                $('#Category').val($(this).children('td').eq('02').text());
                $('#items').val($(this).children('td').eq('03').text());
                $('#hdnID').val($(this).children('td').eq('01').text());
            }


        });
    }

This function will send ajax call with updated values to webmethod and on success empty textboxes of popup and reload page to see changes

function UpdateGrid()
    {
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "Default.aspx/UpdateDB",
            data: JSON.stringify({ category:$('#Category').val() , items: $('#items').val(),id:$('#hdnID').val() }),
            dataType: "json",
            async: false,
            success: function (data) {
                $('#Category').val("");
                $('#items').val("");
                $('#hdnID').val("");
                window.location.reload(true);

            },
            error: function (err) {
                alert(err.responseText);
            }

        });
    }

Here is webmethod

[WebMethod]
public static string UpdateDB(string category, string items,int id)
{
    //Your logic of updating db.Here i am updating on basis of id you can use any feild of your choice        
    return "success";

}

This is only for one row as per your requirement.

like image 2
Mairaj Ahmad Avatar answered Nov 12 '22 11:11

Mairaj Ahmad