Send (Pass) GridView Row details to UserControl (ASCX) using jQuery in ASP.Net

Last Reply 3 months ago By test0101

Posted 3 months ago

in listTab, when click Edit button (in gridview row), will call addnew form with valued and active editTab, when click Update_click button in form addnew will update to database and active listTab with valued just update.

Please help me by code.

this is my code:

1- Main.master

<%@  Master Language="C#" AutoEventWireup="true" CodeBehind="Main.master.cs" Inherits="abc.Main" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" />
    <title></title>
    <link rel="stylesheet" href='http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.3/css/bootstrap.min.css'
        media="screen" />
    <script type="text/javascript" src='http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.3.min.js'></script>
    <script type="text/javascript" src='http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.3/js/bootstrap.min.js'></script>
    
    <asp:ContentPlaceHolder ID="head" runat="server">
    </asp:ContentPlaceHolder>
</head>
<body>
    <form id="main" runat="server">
    <div class="navbar navbar-default" style="font-family: Arial; background-color: #0066CC">
        <div class="container-fluid" style="font-family: Arial">
            <div class="navbar-header" style="font-family: Arial">
                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"
                    aria-expanded="false">
                    <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span><span
                        class="icon-bar"></span><span class="icon-bar"></span>
                </button>
                <a class="navbar-brand" href="#">ASP</a>
            </div>
            <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1" style="font-family: Arial;
                background-color: #1A8CFF">
                <asp:Menu ID="Menu1" runat="server" Orientation="Horizontal" RenderingMode="List"
                    IncludeStyleBlock="false" StaticMenuStyle-CssClass="nav navbar-nav" DynamicMenuStyle-CssClass="dropdown-menu">
                </asp:Menu>
            </div>
        </div>
    </div>
    <script type="text/javascript">
        Sys.WebForms.Menu._elementObjectMapper.getMappedObject = function () {
            return false;
        };
        $(function () {
            $(".navbar-nav li, .navbar-nav a, .navbar-nav ul").removeAttr('style');
            $(".dropdown-menu").closest("li").removeClass().addClass("dropdown-toggle");
            $(".dropdown-toggle").find("a[href='javascript:;']").attr("data-toggle", "dropdown");
            $(".dropdown-toggle").find("a[href='javascript:;'].level1").append("<span class='caret'></span>");
            $(".dropdown-toggle").find("a[href='javascript:;']:not(.level1)").closest('li').addClass('dropdown-submenu');
            $("a.selected").closest("li").addClass("active");
            $("a.selected").closest(".dropdown-toggle").addClass("active");
            $('ul.dropdown-menu [data-toggle=dropdown]').on('click', function (event) {
                event.preventDefault();
                event.stopPropagation();
                $(this).parent().siblings().removeClass('open');
                $(this).parent().toggleClass('open');
            });
        });
    </script>
    <hr />
    <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
    </asp:ContentPlaceHolder>
    </form>
</body>
</html>

2. Main.master.cs

public partial class Main : System.Web.UI.MasterPage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
            DataTable dt = this.GetData(0);
            PopulateMenu(dt, 0, null);
        }
    }
    private DataTable GetData(int parentMenuId)
    {
        DataTable dt = new DataTable();
        dt.Columns.AddRange(new DataColumn[4] { 
            new DataColumn("ParentMenuId"), 
            new DataColumn("MenuId"), 
            new DataColumn("Title"), 
            new DataColumn("Url") });
        dt.Rows.Add(0, 1, "Home", "~/frmTab.aspx");
        // main tab            
        dt.Rows.Add(0, 2, "Services", "javascript:;");
        dt.Rows.Add(0, 3, "About", "javascript:;");
        dt.Rows.Add(0, 4, "Contact ", "~/Contact.aspx");
        dt.Rows.Add(2, 5, "Consulting", "~/Consulting.aspx");
        dt.Rows.Add(2, 6, "Outsourcing ", "~/Outsourcing.aspx");
        dt.Rows.Add(3, 7, "About1", "javascript:;");
        dt.Rows.Add(3, 8, "About2", "~/About2.aspx");
        dt.Rows.Add(7, 9, "About11", "~/About11.aspx");
        dt.Rows.Add(7, 10, "About12", "~/About12.aspx");

        DataTable dtFinal = dt.Clone();
        DataRow[] dr = dt.Select("ParentMenuId=" + parentMenuId);
        if (dr.Length > 0)
        {
            dtFinal = dr.CopyToDataTable();
        }
        return dtFinal;
    }
    private void PopulateMenu(DataTable dt, int parentMenuId, MenuItem parentMenuItem)
    {
        string currentPage = Path.GetFileName(Request.Url.AbsolutePath); foreach (DataRow row in dt.Rows)
        {
            MenuItem menuItem = new MenuItem
            {
                Value = row["MenuId"].ToString(),
                Text = row["Title"].ToString(),
                NavigateUrl = row["Url"].ToString(),
                Selected = row["Url"].ToString().EndsWith(currentPage, StringComparison.CurrentCultureIgnoreCase)
            }; if (parentMenuId == 0)
            {
                Menu1.Items.Add(menuItem);
                DataTable dtChild = this.GetData(int.Parse(menuItem.Value));
                PopulateMenu(dtChild, int.Parse(menuItem.Value), menuItem);
            }
            else
            {
                parentMenuItem.ChildItems.Add(menuItem);
                if (parentMenuId > 0)
                {
                    DataTable dtChild = this.GetData(int.Parse(menuItem.Value));
                    PopulateMenu(dtChild, int.Parse(menuItem.Value), menuItem);
                }
            }
        }
    }
}

3- frmTab.aspx

<%@ Page Title="" Language="C#" MasterPageFile="~/Main.master" UnobtrusiveValidationMode="None"
    AutoEventWireup="true" CodeBehind="frmTab.aspx.cs" Inherits="abc.frmTab" %>

<%@ Register Src="~/frmList.ascx" TagPrefix="uc" TagName="list" %>
<%@ Register Src="~/frmAddnew.ascx" TagPrefix="uc" TagName="addnew" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
    <div class="panel panel-default" style="width: auto; padding: 6px; margin: 6px">
        <div id="dvTab">
            <ul class="nav nav-tabs" role="tablist" style="font-weight: bold">
                <li runat="server" id="idListtab"><a href="#Listtab" style="outline: none" aria-controls="Listtab"
                    role="tab" data-toggle="tab">List</a></li>
                <li runat="server" id="idAddnew"><a href="#Addnew" style="outline: none" aria-controls="Addnew"
                    role="tab" data-toggle="tab">Add new</a></li>
                <li runat="server" id="idEdittab"><a href="#Edittab" style="outline: none" aria-controls="Edittab"
                    role="tab" data-toggle="tab">Edit</a></li>
            </ul>
            <div class="tab-content" style="padding-top: 5px">
                <!-- <div role="tabpanel" class="tab-pane" id="Listtab"> -->
                <div role="tabpanel" class="tab-pane active" id="Listtab">
                    <uc:list ID="mylist" runat="server" />
                </div>
                <div role="tabpanel" class="tab-pane active" id="Addnew">
                    <uc:addnew ID="myaddnew" runat="server" />
                </div>
                <div role="tabpanel" class="tab-pane" id="Edittab">
                    <uc:addnew ID="myaddnew" runat="server" />
                </div>
            </div>
        </div>
    </div>
    <!-- Panel  End-->
    <asp:HiddenField ID="HiddenTab" runat="server" />
    <script type="text/javascript">
        function Tabs() {
            var Tab = $("#<%=HiddenTab.ClientID%>");
            var tabId = Tab.val() != "" ? Tab.val() : "Listtab";
            $('#dvTab a[href="#' + tabId + '"]').tab('show');
            $("#dvTab a").click(function () {
                Tab.val($(this).attr("href").substring(1));
                //replace("#", ""));                     
                //substring(1));                 
            });
        }
        function pageLoad() {
            Tabs();
        }         
    </script>
</asp:Content>

4- frmTab.cs

using System;
namespace abc
{
    public partial class frmtab : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            HiddenTab.Value = "Listtab";
            idEdittab.Visible = false;
        }
    }
}

5- frmAddnew.ascx

<%@ Page Title="" Language="C#" MasterPageFile="~/Main.master" UnobtrusiveValidationMode="None"
    AutoEventWireup="true" CodeBehind="frmaddnew.aspx.cs" Inherits="abc.frmaddnew" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
    <div class="table-responsive">
        <table style="width: auto" class="table table-striped">
            <tr>
                <td class="td-align-Right">
                    <asp:Label ID="Label1" CssClass="btn btn-labeled btn-default" runat="server" Text="Name"></asp:Label>
                </td>
                <td class="td-align-left">
                    <asp:TextBox ID="txtName" CssClass="form-control" runat="server" ValidationGroup="reg"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtName"
                        ErrorMessage="*" ForeColor="#FF0066" ValidationGroup="reg"></asp:RequiredFieldValidator>
                </td>
            </tr>
            <tr>
                <td class="td-align-Right">
                    <asp:Label ID="Label2" runat="server" CssClass="btn btn-labeled btn-default" Text="Mobile Number"></asp:Label>
                </td>
                <td class="td-align-left">
                    <asp:TextBox ID="txtMobile" CssClass="form-control" runat="server" ValidationGroup="reg"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="txtMobile"
                        ErrorMessage="*" ForeColor="#FF0066" ValidationGroup="reg"></asp:RequiredFieldValidator>
                    <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="txtMobile"
                        ErrorMessage="Invalid Number" ForeColor="#CC3300" ValidationExpression="\d{10}"
                        ValidationGroup="reg"></asp:RegularExpressionValidator>
                </td>
            </tr>
            <tr>
                <td class="td-align-Right">
                    <asp:Label ID="Label3" runat="server" CssClass="btn btn-labeled btn-default" Text="Email"></asp:Label>
                </td>
                <td class="td-align-left">
                    <asp:TextBox ID="txtEmail" CssClass="form-control" runat="server" ValidationGroup="reg"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="txtEmail"
                        ErrorMessage="*" ForeColor="#FF0066" ValidationGroup="reg"></asp:RequiredFieldValidator>
                    <asp:RegularExpressionValidator ID="RegularExpressionValidator2" runat="server" ControlToValidate="txtEmail"
                        ErrorMessage="Invalid Email" ForeColor="#CC3300" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"
                        ValidationGroup="reg"></asp:RegularExpressionValidator>
                </td>
            </tr>
            <tr>
                <td class="td-align-Right">
                    &nbsp;
                </td>
                <td>
                    <asp:Button ID="Save" CssClass="btn-danger btn-sm" runat="server" Text="Save add new"
                        OnClick="Save_Click" ValidationGroup="reg" />&nbsp;
                    <asp:Button ID="Update" CssClass="btn-danger btn-sm" runat="server" Text="save update"
                        OnClick="Update_Click" ValidationGroup="reg" />&nbsp;
                    <asp:Button ID="Reset" runat="server" CssClass="btn-danger btn-sm" Text="Reset" OnClick="Reset_Click"
                        CausesValidation="False" />&nbsp;
                </td>
            </tr>
        </table>
    </div>
</asp:Content>

6- frmAddnew.cs

using System;
namespace abc
{
    public partial class frmAddnew : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
        protected void Save_Click(object sender, EventArgs e)
        {
            try
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("insert into register values('" + txtName.Text + "','" + txtMobile.Text + "','" + txtEmail.Text + "')", con);
                cmd.ExecuteNonQuery();
                ScriptManager.RegisterStartupScript(Page, this.GetType(), "popup", "alert('Register Sucessfully')", true);
                GridView1.DataSource = null;
                GridView1.DataBind();
                // i do not HOW TO ACTIVE TAB AND OPEN                
                HiddenTab.Value = "Addnew"; // ??????            
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(Page, this.GetType(), "Error", "alert('" + "ERROR : " + ex.Message.ToString() + "')", true);
            }
            finally
            {
                con.Close();
            }
        }
        protected void Update_click(object sender, EventArgs e)
        {
            try
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("update register set name= '" + txtName.Text + "', mobile='" + txtMobile.Text + "', email='" + txtEmail.Text + "'", con);
                cmd.ExecuteNonQuery();
                ScriptManager.RegisterStartupScript(Page, this.GetType(), "popup", "alert('upadate Sucessfully')", true);
                GridView1.DataSource = null;
                GridView1.DataBind();
                // i do not HOW TO ACTIVE TAB AND OPEN               
                HiddenTab.Value = "Listtab"; // ??????            
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(Page, this.GetType(), "Error", "alert('" + "ERROR : " + ex.Message.ToString() + "')", true);
            }
            finally
            {
                con.Close();
            }
        }
        protected void Reset_Click(object sender, EventArgs e)
        {
            txtName.Text = string.Empty; txtMobile.Text = "";
            txtEmail.Text = "";
            txtName.Focus(); HiddenTab.Value = "Addnew";
        }
    }
}

7- frmList.ascx

<%@ Page Title="" Language="C#" MasterPageFile="~/Main.master" UnobtrusiveValidationMode="None"
    AutoEventWireup="true" CodeBehind="frmList.aspx.cs" Inherits="abc.frmList" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
    <div class="table-responsive">
        <asp:GridView ID="GridView1" AlternatingRowStyle-CssClass="alt" PagerStyle-CssClass="pgr"
            CssClass="SGrid" runat="server" AutoGenerateColumns="False">
            <AlternatingRowStyle CssClass="alt" />
            <Columns>
                <asp:TemplateField HeaderText="Name">
                    <ItemTemplate>
                        <asp:Label ID="Label4" runat="server" Text='<%# Eval("name") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Mobile Number">
                    <ItemTemplate>
                        <asp:Label ID="Label5" runat="server" Text='<%# Eval("mobile") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Email Id">
                    <ItemTemplate>
                        <asp:Label ID="Label6" runat="server" Text='<%# Eval("email") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Action">
                    <ItemTemplate>
                        <asp:Button ID="bttEdit" runat="server" Text="Edit" OnClick="bttEdit_Click" Class="btn-primary" />
                        <asp:Label ID="lblEmail" runat="server" Text='<%#Eval("email") %>' Visible="false"></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
            <PagerStyle CssClass="pgr" />
        </asp:GridView>
        <input type="hidden" runat="server" id="hiddEmail" />
    </div>
</asp:Content>

8- frmList.cs

using System;
namespace abc
{
    public partial class frmlist : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e) { GridView(); }
        protected void bttEdit_Click(object sender, EventArgs e)
        {           // I DON NOT KNOW HOW TO ACTIVE EDIT TAB AND CODE HERE FOR GET ALL INFOR FROM ONE GRIDVIEW ROW AND DISPLAY ON FORM ADD NEW TO UPDATE THIS RECORD
            HiddenTab.Value = "Edittab";  // ?????
        }

        protected void GridView()
        {
            try
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("select * from register", con);
                SqlDataAdapter adp = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                adp.Fill(ds);
                if (ds.Tables[0].Rows.Count > 0)
                {
                    GridView1.DataSource = ds;
                    GridView1.DataBind();
                }
                else
                {
                    ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
                    GridView1.DataSource = ds;
                    GridView1.DataBind();
                    int columncount = GridView1.Rows[0].Cells.Count;
                    GridView1.Rows[0].Cells.Clear();
                    // GridView2.FooterRow.Cells.Clear();                    
                    GridView1.Rows[0].Cells.Add(new TableCell());
                    GridView1.Rows[0].Cells[0].ColumnSpan = columncount;
                    GridView1.Rows[0].Cells[0].Text = "No Records Found";
                } HiddenTab.Value = "Listtab";
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(Page, this.GetType(), "Error", "alert('" + "ERROR : " + ex.Message.ToString() + "')", true);
            }
            finally
            {
                con.Close();
            }
        }
    }
}

 

Posted 3 months ago Modified on 3 months ago

Recent i can get variable from gridview row on frmList.ascx and pass to frmAddnew.ascx for update edit. 

<%@ Page Title="" Language="C#" MasterPageFile="~/Main.Master" EnableEventValidation="false" UnobtrusiveValidationMode="None" AutoEventWireup="true" CodeBehind="frmTab.aspx.cs" Inherits="WebFormDemo01.frmTab" %>

<%@ Register Src="~/frmList.ascx" TagPrefix="uc" TagName="list" %>
<%@ Register Src="~/frmAddnew.ascx" TagPrefix="uc" TagName="addnew" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">    
    
        <script>
            function Pass(row) {//this method is used to pass value from frmList to frmAddnew
                var id = $("#ContentPlaceHolder1_mylist_GridView1_hidId_" + row).val();
                var name = $("#ContentPlaceHolder1_mylist_GridView1_Label4_" + row).html();
                var phone = $("#ContentPlaceHolder1_mylist_GridView1_Label5_" + row).html();
                var email = $("#ContentPlaceHolder1_mylist_GridView1_Label6_" + row).html();
                $("#ContentPlaceHolder1_Addnew1_txtName").val(name);
                $("#ContentPlaceHolder1_Addnew1_txtMobile").val(phone);
                $("#ContentPlaceHolder1_Addnew1_txtEmail").val(email);
                $("#ContentPlaceHolder1_Addnew1_hidUId").val(id);//store customer id in hiddenfield so that the program could know which record in DB it's dealing with
            }
        </script>
</asp:Content>

 

    public partial class frmList : System.Web.UI.UserControl
    {
        public static string constr = "server=(local);uid=sa;database=test;pwd=111111; MultipleActiveResultSets=true"; // for Local

        SqlConnection con = new SqlConnection(constr);

        protected void Page_Load(object sender, EventArgs e)
        {
            GridView();           
        }

        protected void bttEdit_Click(object sender, EventArgs e)
        {
            //  GridViewRow row = ((Button)sender).Parent.Parent as GridViewRow;
            //  string index = row.Cells[0].ClientID.Substring(row.Cells[0].ClientID.Length - 1);//get in which row of Gridview the Edit button triggered this event

            Button clickedButton = (Button)sender;
            GridViewRow row = (GridViewRow)clickedButton.Parent.Parent;
            int index = row.RowIndex;


            ScriptManager.RegisterStartupScript(Page, this.GetType(), "goEdit", "$('#dvTab a[href=\"#Edittab\"]').tab('show');$('#ContentPlaceHolder1_idEdittab').show();", true);//show the Edittab and the Edittab<a>
            ScriptManager.RegisterStartupScript(Page, this.GetType(), "PassValue", "Pass(" + index + ")", true);//fire the pass(row) method to pass values
        }