Friday, December 30, 2011

Accessing GridView controls using Client side code/ Jquery


Accessing GridView controls from server side is such a easy task, but when we access GridView controls from client side then generally we face problem, because if we use getElementById() to get GridView controls then it creates complexity.

In this article, I am going to explain – How you can access GridView controls from client side?  By using this method not only you can access single control but also you can access more than one control with single line of code.

In this example, I am using Jquery. Here I am accessing GridView control (LinkButton) and hiding/showing that control from client side.

First, I have defined one blank CSS class - clsFind

<style type ="text/css">
    .clsFind
    {
    }
</style>


Note-  


Using this CSS class only, we will access GridView Control.

Now I have defined these two functions to get GridView control (LinkButton) and after that I am hiding/ showing that control.

<script type ="text/javascript" >
    //Function to Hide control
    function HideControl() {
        var con = $(".clsFind");
        con.hide();
        return false;
    }

    //Function to Show control
    function ShowControl() {
        var con = $(".clsFind");
        con.show();
        return false;
    }
    </script>


Note-

 
HideControl function will be called when you will press Hide Control Button.
ShowControl function will be called when you will press Show Control Button.

Now I have designed GridView like this-



GridView

Here is .aspx code-

 
<asp:GridView ID="GrdEmpData" runat="server" AutoGenerateColumns="false"
                onrowdeleting="GrdEmpData_RowDeleting" Width ="50%">
                <Columns>
                    <asp:TemplateField HeaderText="EmpId" ItemStyle-HorizontalAlign  ="Left"  ItemStyle-Width ="20%">
                        <ItemTemplate>
                            <asp:Label ID="lblEmpId" runat="server" Text='<% # Eval("EmpId") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="EmpName" ItemStyle-HorizontalAlign  ="Left"  ItemStyle-Width ="30%">
                        <ItemTemplate>
                            <asp:Label ID="lblEmpName" runat="server" Text='<% # Eval("EmpName") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="DeptId" ItemStyle-HorizontalAlign  ="Left"  ItemStyle-Width ="30%">
                        <ItemTemplate>
                            <asp:Label ID="lblDeptName" runat="server" Text='<% # Eval("DeptName") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField  HeaderText="Delete" ItemStyle-HorizontalAlign  ="Left"  ItemStyle-Width ="20%">
                        <ItemTemplate>
                            <asp:LinkButton ID="lnkDelete" runat="server" Text="Delete" CommandName ="delete" CssClass  ="clsFind"></asp:LinkButton>
                        </ItemTemplate>
                    </asp:TemplateField>
                </Columns>
            </asp:GridView>
            <br />
        <asp:Button ID="btnShowControl" runat="server" Text="Show Delete Button" OnClientClick ="return ShowControl();"/>
        <asp:Button ID="btnHideControl" runat="server" Text="Hide Delete Button" OnClientClick="return HideControl();" />


Now done, when you will press Hide Control Button then delete LinkButton will be disappeared, and your GridView will be like this-



Hiding Control in GridView


To show LinkButton again, you can press Show Control Button.

Note-

 
The main advantage of this approach is that, you can access more than one controls using single line of code. For that,  you have to code like this-

 <asp:LinkButton ID="lnkDelete" runat="server" Text="Delete" CommandName ="delete" CssClass  ="clsFind"></asp:LinkButton>

 <asp:LinkButton ID="lnkShow" runat="server" Text="show"  CssClass ="clsFind"></asp:LinkButton>

 
Means, you have to give same CSS class for controls. Now when you will use this statement –

 var con = $(".clsFind");

Then using "con" object only, you can set properties for lnkDelete and lnkEdit  LinkButtons. Like this-


  con.hide();

This approach is useful when we have multiple controls and we want to set same type of values for their properties.


Update  :

To get control value :


Suppose you have LinkButton inside GridView with Text "Delete"

<asp:TemplateField HeaderText="Delete" ItemStyle-HorizontalAlign="Left" ItemStyle-Width="20%">
  <ItemTemplate>
      <asp:LinkButton ID="lnkDelete" runat="server" Text="Delete"  CommandName="delete"  CssClass="clsFind"></asp:LinkButton>
   </ItemTemplate>
</asp:TemplateField>


Now to get control value, We have one button outside of the GridVIew


 <asp:Button ID="btnGetValue" runat="server" Text="Get Value" OnClientClick="return GetValue();" />


Use these code to get value-

 <script type="text/javascript">

    //Function to get control value

        function GetValue() {
            var con = $(".clsFind");
           
  // Way 1:To get combine text of all link button in GridView
            var combineText = con.text()
            alert(combineText);


  //Way 2: To get text of any particular link button in GridView (for first row)
            var firstRowLinkButtonText1 = con[0].innerHTML
            alert(firstRowLinkButtonText );


  //Way 3: To get text of any particular link button in GridView (for first row)

            var firstRowLinkButtonText2 = $('#GrdEmpData tr>td>a[id*=lnkDelete]')[0].innerHTML;
            alert(firstRowLinkButtonText2);
 
            return false;
        }
   
    </script>




Try these way and let me know.

 

Thanks

Tuesday, December 27, 2011

GridView Edit , Update and Delete


GridView-

 
GridView is one of the controls of type, Data Control in ASP.Net, which is used for data representation on web page. GridView not only is used for showing data but also we can perform operation like- Edit, Update, Cancel  and Delete using GridView.
 

GridView has some in-built events, using these events you can perform these operations. For this you have to implement following events of GridView-

1.     GrdEmpData_RowEditing
2.     GrdEmpData_RowDeleting
3.     GrdEmpData_RowUpdating
4.     GrdEmpData_RowCancelingEdit

By implementing these events, you can perform Edit, Delete and Update operations in GridView.

In this article I am going to explain, How you can perform these operations in GridView? 

First design GridView like this-

.aspx code-

 
 <asp:GridView ID="GrdEmpData" runat="server" AutoGenerateColumns="false"
               Width ="50%" onrowcancelingedit="GrdEmpData_RowCancelingEdit"
             onrowdeleting="GrdEmpData_RowDeleting" onrowediting="GrdEmpData_RowEditing"
             onrowupdating="GrdEmpData_RowUpdating" >
                <Columns>
                    <asp:TemplateField HeaderText="EmpId" ItemStyle-HorizontalAlign  ="Left"  ItemStyle-Width ="10%">
                        <ItemTemplate>
                            <asp:Label ID="lblEmpId" runat="server" Text='<% # Eval("EmpId") %>'></asp:Label>
                        </ItemTemplate>
                     </asp:TemplateField>
                    <asp:TemplateField HeaderText="EmpName" ItemStyle-HorizontalAlign  ="Left"  ItemStyle-Width ="40%">
                        <ItemTemplate>
                            <asp:Label ID="lblEmpName" runat="server" Text='<% # Eval("EmpName") %>'></asp:Label>
                        </ItemTemplate>
                         <EditItemTemplate >
                            <asp:TextBox ID="TxtEmpName" runat="server" Text='<% # Eval("EmpName") %>'></asp:TextBox>
                        </EditItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Salary" ItemStyle-HorizontalAlign  ="Left"  ItemStyle-Width ="20%">
                        <ItemTemplate>
                            <asp:Label ID="lblSalary" runat="server" Text='<% # Eval("Salary") %>'></asp:Label>
                        </ItemTemplate>
                        <EditItemTemplate >
                            <asp:TextBox ID="TxtSalary" runat="server" Text='<% # Eval("Salary") %>'></asp:TextBox>
                        </EditItemTemplate>
                    </asp:TemplateField>
                    <asp:CommandField ShowEditButton ="true"  HeaderText ="Edit" ItemStyle-Width ="20%"/>
                    <asp:TemplateField  HeaderText="Delete" ItemStyle-HorizontalAlign  ="Left"  ItemStyle-Width ="10%">
                        <ItemTemplate>
                            <asp:LinkButton ID="lnkDelete" runat="server" Text="Delete" CommandName ="delete"   CommandArgument='<% # Eval("EmpId") %>' OnClientClick ="return confirm('Do you want to delete this record?;')"></asp:LinkButton>
                        </ItemTemplate>
                    </asp:TemplateField>
                </Columns>
            </asp:GridView>



In above .aspx code, I have designed one GridView with 5 columns - EmpId, EmpName, Salary and 2 columns for Edit and Delete records.

For editing,   I have taken ComnmandField , This is built-in column for GridView by setting "ShowEditButoin= true" we can add it to GridVIew like this-

   <asp:CommandField ShowEditButton ="true"  HeaderText ="Edit" ItemStyle-Width ="20%"/>

For deleting,   I have taken LinkButton in TemplateField  because I want to show delete confirmation . Like this-

  <ItemTemplate>
      <asp:LinkButton ID="lnkDelete" runat="server" Text="Delete" CommandName ="delete"   CommandArgument='<% # Eval("EmpId") %>' OnClientClick ="return confirm('Do you want to delete this record?;')">
       </asp:LinkButton>
   </ItemTemplate>


Here first, I am showing delete confirmation message using JavaScript.

.cs code-

To bind record to the GridView , I have written one function GetData(), After setting the record from server GridView will be bounded with fetched record in Page_Load() event. For increasing the performance, I have called GetData() function in if() condition, so that at the time of postback GridView will not be bounded again.

protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (!IsPostBack)
            {
                //Binding Data to GridView
                GetData();
            }
        }
        catch (Exception ex)
        {
            Response.Write(@"<script>alert('" + ex.Message + "')</script>");
        }
    }
  
    //Function to get data from database
    private void GetData()
    {
        try
        {
            DataTable dt = null;
            string conString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
            SqlConnection con = new SqlConnection(conString);
            SqlDataAdapter da = new SqlDataAdapter("select * from tab_EmpMaster", con);
            dt = new DataTable();
            da.Fill(dt);
            GrdEmpData.DataSource = dt;
            GrdEmpData.DataBind();
        }
        catch (Exception ex)
        {
            Response.Write(@"<script>alert('" + ex.Message + "')</script>");
        }
    }


To perform operation on GridView, I have created one generic function. This function will accept SQL query as input and it will execute this query using  SqlCommand object. This function is specific for DML operations like- Insert, Update and Delete.

//Function to perform DML
    private void PerformDML(string strQuery)
    {
        try
        {
            string conString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
            SqlConnection con = new SqlConnection(conString);
            con.Open();
            SqlCommand cmd = new SqlCommand(strQuery, con);
            cmd.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            Response.Write(@"<script>alert('" + ex.Message + "');</script>");
        }
    }


To perform operation on GridView, you have to just pass SQL query in this function. Here we need to frame query based on GridView actions. Now I am implementing GridView events to perform operations.

//Code to edit

    protected void GrdEmpData_RowEditing(object sender, GridViewEditEventArgs e)
    {
        try
        {
            GrdEmpData.EditIndex = e.NewEditIndex;
            //Rebind Grid
            GetData();
        }
        catch (Exception ex)
        {
          Response.Write(@"<script>alert('" + ex.Message + "')</script>");
        }
    }


 When you will click on edit button, then GridView will display Update and Cancel button.


//Code to cancel

    protected void GrdEmpData_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        try
        {
            //Setting Grid to non editable mode
            GrdEmpData.EditIndex = -1;
            //Rebind Grid
            GetData();
        }
        catch (Exception ex)
        {
            Response.Write(@"<script>alert('" + ex.Message + "')</script>");
        }
    }


//Code to Update

    protected void GrdEmpData_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        try
        {
            Label lblEmpId = (Label)GrdEmpData.Rows[e.RowIndex].FindControl("lblEmpId");
            TextBox txtEmpName = (TextBox)GrdEmpData.Rows[e.RowIndex].FindControl("TxtEmpName");
            TextBox txtSalary = (TextBox)GrdEmpData.Rows[e.RowIndex].FindControl("TxtSalary");

            if (lblEmpId != null && txtEmpName !=null && txtSalary !=null)
            {
                int empId = Convert.ToInt32(lblEmpId.Text);
                string strQuery = "update tab_EmpMaster set empname='" + txtEmpName.Text + "', salary=" + Convert.ToDecimal(txtSalary.Text) + " where empid=" + Convert.ToInt32(lblEmpId.Text) + " ";
                PerformDML(strQuery);
                Response.Write("<script>alert('Record updated  successfully.')</script>");
                //Setting Grid to non editable mode
                GrdEmpData.EditIndex = -1;
                //Rebind Grid
                GetData();
            }

        }
        catch (Exception ex)
        {
            Response.Write(@"<script>alert('" + ex.Message + "')</script>");
        }
    }


//Code to Delete

    protected void GrdEmpData_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        try
        {
            Label lblEmpId = (Label)GrdEmpData.Rows[e.RowIndex].FindControl("lblEmpId");
            if (lblEmpId != null)
            {
                int empId = Convert.ToInt32(lblEmpId.Text);
                string strQuery="delete from tab_EmpMaster where empid=" + empId + " ";
                PerformDML(strQuery);
                Response.Write("<script>alert('Record deleted successfully.')</script>");
                //Rebind Grid
                GetData();
            }

        }
        catch (Exception ex)
        {
            Response.Write(@"<script>alert('" + ex.Message + "')</script>");
        }
    }


Note-  


After clicking delete button, you will get confirmation box.

In all operation, first we need to get the id for particular record to which we want to update or delete, because based on that only operation will be performed. To get Control's value from GridView I have used FindControl() method. This method returns particular object if it is found otherwise it returns null value.

By using this code you can easily perform operations on GridView.


Thanks

Sunday, December 25, 2011

Jquery popup window in ASP.Net.


For every Application popup window plays very important role, because it makes more user friendly to the Application. Generally popup window is used for following reasons-

-To alert user
-To show information
-To take input

For other cases also you can use popup window.

In this article I am going to explain, How you can display popup in your Application?


Here I am JQuery popup.To use JQuery popup, first you have to include following JS and CSS files in your project.

JS Files-

jquery-1.4.2.js
jquery-ui-1.8.2.custom.min.js

CSS Files-

jquery-ui-1.8.4.custom.css

Just place these files in your project like this-



Solution Explorer


Now just include these files in your .aspx file like this-

<head runat="server">
    <title>Jquery PopUp Demo</title>
  
    <link href="JQueryCSS/jquery-ui-1.8.4.custom.css" rel="stylesheet" type="text/css" />
    <script src="JQuerJS/jquery-1.4.2.js" type="text/javascript"></script>
    <script src="JQuerJS/jquery-ui-1.8.2.custom.min.js" type="text/javascript"></script>
  
    <script type="text/javascript">
        function funDisplayPopUp() {
            $('#dialogDiv').dialog({ resizable: false, height: 200, modal: true });
            return false;
        }
    </script>

</head>
<body>
    <form id="form1" runat="server">
    <center>
    <div>
        <asp:Button ID="btnDisplayPopup" runat="server" Text ="Display Popup" OnClientClick="return funDisplayPopUp();" />
        <div id="dialogDiv" title="Information" style ="display:none ">
             Hello Dear
        </div>
    </div>
    </center>
    </form>
</body>


Note-  


In this example first set display:none for div, which will be displayed as popup.

<div id="dialogDiv" title="Information" style ="display:none ">
             Hello Dear
</div>
 


Now done, when you will run this project, you will get one button control on form, when you will click on that button one popup window will be displayed like this-


Jquery popup window


Note- You can put server controls in this popup to control action based on your need.

Thanks