Showing posts with label Gridview. Show all posts
Showing posts with label Gridview. Show all posts

Friday, August 16, 2013

How to Bind Nested Gridview from Database in asp.net with C# Example

No comments :
Binding nested gridview and work with nested gridview is something different than normal gridview. Here I want to bind nested gridview means Gridview inside Gridview.In this post we will dynamically bind both gridviews parent gridview and nested gridview.

In my previous post "How to Dynamically Bind A Gridview From Database" i had explained that how to bind gridview at run time. Here in this example i have binded both gridviews dynamically.

In this post we are creating like this; There is one Image in Outer Grid when you click that image nested grid will be displayed and when press that image again nested grid will be hided.

Here i have used two image which is swapped using Java script and jquery to change the image according to nested grid is open or close. Here in this example when nested grid is open minus sign image and when closed Plus Sign image is displayed.

In this example nested gridview will be binded with parent gridview on RowDataBound event of parent grid view. And i'm using Another template field of ID to identify row of nested grid view.

Here is the Image Hoe it Looks Like:-

Nested Gridview

Here is my tables



Parent Table
efnamenvarchar(50)Unchecked
IDintUnchecked
elnamenvarchar(50)Unchecked
eaddnvarchar(50)Unchecked
ephonenvarchar(50)Unchecked


Child Table
idintUnchecked
Projectnvarchar(50)Unchecked

Source Code in asp.net:-


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!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 runat="server">
    <title></title>
    <style type="text/css">
        .style1 {
            width: 100%;
        }
    </style>

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

    <script type="text/javascript">
        $("[src*=plus]").live("click", function () {
            $(this).closest("tr").after("<tr><td></td><td colspan = '999'>" + $(this).next().html() + "</td></tr>")
            $(this).attr("src", "minus.jpeg");
        });
        $("[src*=minus]").live("click", function () {
            $(this).attr("src", "plus.jpeg");
            $(this).closest("tr").next().remove();
        });
    </script>

</head>
<body>
    <form id="form1" runat="server">
        <div>
        </div>
        <table class="style1">
            <tr>
                <td align="center">
                    <h2>Nested Gridview Bind</h2>
                </td>
            </tr>
            <tr>
                <td align="center">
                    <asp:GridView ID="pgridview" runat="server" AutoGenerateColumns="False" CellPadding="4"
                        ForeColor="#333333" GridLines="None" OnRowDataBound="pgridview_RowDataBound" DataKeyNames="ID">
                        <AlternatingRowStyle BackColor="White" ForeColor="#284775"/>
                        <EditRowStyle BackColor="#999999" />
                        <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                        <HeaderStyle BackColor="#41B7D8" Font-Bold="True" ForeColor="White" />
                        <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
                        <Columns>
                            <asp:TemplateField>
                                <ItemTemplate>
                                    <img alt="" style="cursor: pointer" height="20px" width="20px" src="plus.jpeg" />
                                    <asp:Panel ID="Panel1" Style="display: none" runat="server">
                                        <asp:GridView ID="ngridview" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None"
                                            AutoGenerateColumns="False" BorderColor="#41B7D8">
                                            <EditRowStyle BackColor="#999999" />
                                            <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                                            <HeaderStyle BackColor="#41B7D8" Font-Bold="True" ForeColor="White" />
                                            <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
                                            <Columns>
                                                <asp:TemplateField HeaderText="id">
                                                    <ItemTemplate>
                                                        <asp:Label ID="lblid" runat="server" Text='<%#Eval("id") %>'></asp:Label>
                                                    </ItemTemplate>
                                                </asp:TemplateField>
                                                <asp:TemplateField HeaderText="Projects">
                                                    <ItemTemplate>
                                                        <asp:Label ID="lproject" runat="server" Text='<%#Eval("Project") %>'></asp:Label>
                                                    </ItemTemplate>
                                                </asp:TemplateField>
                                            </Columns>
                                        </asp:GridView>
                                    </asp:Panel>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField Visible="false">
                                <ItemTemplate>
                                     <asp:Label ID="lpid" runat="server" Text='<%#Eval("ID")%>'></asp:Label>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="EMP_FIRSTNAME">
                                <ItemTemplate>
                                    <asp:Label ID="lfname" runat="server" Text='<%#Eval("efname")%>'></asp:Label>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="EMP_LASTNAME">
                                <ItemTemplate>
                                    <asp:Label ID="llname" runat="server" Text='<%#Eval("elname") %>'></asp:Label>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="ADDRESS">
                                <ItemTemplate>
                                    <asp:Label ID="ladd" runat="server" Text='<%#Eval("eadd") %>'></asp:Label>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="PHONE NO">
                                <ItemTemplate>
                                    <asp:Label ID="lphone" runat="server" Text='<%#Eval("ephone") %>'></asp:Label>
                                </ItemTemplate>
                            </asp:TemplateField>
                        </Columns>
                    </asp:GridView>
                </td>
            </tr>

        </table>
    </form>
</body>
</html>

Code in C#:-


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection(@"Data Source=SQLDB;Initial Catalog=Demo;Persist Security Info=True;User ID=Demoh;Password=Demo1@");
        con.Open();
        string q = "select * from Employee_tbl";
       
        SqlDataAdapter adpter = new SqlDataAdapter(q, con);

        DataTable dt = new DataTable();
        adpter.Fill(dt);

        pgridview.DataSource = dt;
        pgridview.DataBind();

        con.Close();
    }
    protected void pgridview_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Label id = (Label)e.Row.FindControl("lpid"); // Id of the parent grid record to Identifiy related recors in child table
            GridView gr = (GridView)e.Row.FindControl("ngridview");
            SqlConnection con = new SqlConnection(@"Data Source=SQLDB;Initial Catalog=Demo;Persist Security Info=True;User ID=Demoh;Password=Demo1@");
            con.Open();
            // string q = "select * from Emp";
            string q1 = "select id,Project from Employ_Salary where id="+id.Text;
            // SqlDataAdapter adpter = new SqlDataAdapter(q, con);
            SqlDataAdapter ad1 = new SqlDataAdapter(q1, con);
            DataTable dt1 = new DataTable();
            // DataTable dt = new DataTable();
            ad1.Fill(dt1);

            gr.DataSource = dt1;
            gr.DataBind();

            con.Close();
        }
    }
}

Read More

Monday, August 5, 2013

How to Read data from XML File and Bind to Gridview in asp.net with C# - Example

No comments :
In previous article we have learned How to Import Data From Excel file to Database in Asp.net with C# - Example. an you can find other Gridview example here Gridview Here in this post we will discuss how to Read Data from XML file and bind it to grid view. It is very simple task you just have to create one DataSet object and call the method ReadXml() you have to pass one argument in it, which is file name from which you want to read data.



first of all i have one xml file Contact.xml it is as per following.

<?xml version="1.0" encoding="utf-8" ?>
<Contacts>
  <Contact>
    <Name>steve jobs</Name>
    <Number>0081663465</Number>
    <Address>USA</Address>
  </Contact>
  <Contact>
    <Name>Bill gates</Name>
    <Number>05601215</Number>
    <Address>US</Address>
  </Contact>
  <Contact>
    <Name>Peter Capaldi</Name>
    <Number>005642313</Number>
    <Address>USA</Address>
  </Contact>
</Contacts>

Here is the screen shot of my grid which is binded from XML file


Source Code in Asp.net:-


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="XMLtoGrid.aspx.cs" Inherits="BlogCodeTester.XMLtoGrid" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None">
                <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
                <EditRowStyle BackColor="#999999" />
                <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                <HeaderStyle BackColor="#41B7D8" Font-Bold="True" ForeColor="White" />
                <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
            </asp:GridView>

        </div>
    </form>
</body>
</html>

Code in C#:-

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace BlogCodeTester
{
    public partial class XMLtoGrid : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            readFromXML();
        }
        private void readFromXML()
        {
            string myfile = @Server.MapPath("~/Contact.xml");
            DataSet ds = new DataSet();
            ds.ReadXml(myfile);
            if (ds.Tables[0].Rows.Count > 0)
            {
                GridView1.DataSource = ds;
                GridView1.DataBind();
            }
            else
            {
                Response.Write("No data to display");
            }
        }
    }
}
Read More

Wednesday, July 24, 2013

How to Import Data From Excel file to Database in Asp.net with C# - Example

No comments :

Introduction:

Hello Friends, in previous post we learned HOW TO EXPORT DATA FROM GRID TO EXCEL SHEET. Now in this post we will learn How to Import data from Excel file to Gridview and store it to MS SQL Server or Database.


Many times we face a situation where we have readily available excel sheets having large data that needs to be imported in database.

In the following example First of all we upload an Excel Sheet from FileUpload Control then this records will be displayed in Gridview. when we press the Import Button all the records will we inserted into Database.

Here is my Excel Sheet:-


Database Table (SQL Server 2008).:-


Now we have table and excel file so first we will import data from excel sheet for that i have used System.Data.OleDb library now we create connection to Excel sheet and than check the extension of uploaded file because connection string for .xls and .xlsx are different.

Create OLE DB connection and command which is used to extract data from Excel File. we will store this data to data table then bind to gridview in final step will insert all the records of Gird into Database using SqlBulkCopy. 

SqlBulkCopy allows us to insert multiple records in Database Table in just few lines of code.

Here Is the Screen Shots:-

click on Brows Button and Choose Excel File.

Excel Sheet data Records are binded to Gridview. When you click "Store To Database" button all the records in gridview will be inserted to database table.

Source Code in Asp.net:-

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!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 runat="server">
    <title></title>

</head>
<body>
    <form id="form1" runat="server">
        <center>
            <table>
                <tr>
                    <td class="auto-style2">
                        <asp:FileUpload ID="FileUpload1" runat="server" /></td>
                </tr>
                <tr>
                    <td class="auto-style5">
                        <asp:Button ID="btnUpload" runat="server" Height="30px"
                            Text="Upload" Width="92px" OnClick="btnUpload_Click" BackColor="#41B7D8" ForeColor="White" Font-Bold="true" BorderStyle="None" /></td>
                </tr>
                <tr>
                    <td class="auto-style4">
                        <asp:GridView ID="GridView1" runat="server" CellPadding="4" EnableModelValidation="True" ForeColor="#333333" GridLines="None" Height="177px" Width="217px">
                            <AlternatingRowStyle BackColor="White" ForeColor="#284775" />

                            <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                            <HeaderStyle BackColor="#41B7D8" Font-Bold="True" ForeColor="White" />
                            <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
                            <RowStyle BackColor="#F7F6F3" ForeColor="#333333" HorizontalAlign="Center" />
                        </asp:GridView>
                    </td>
                </tr>
                <tr>
                    <td class="auto-style6">
                        <asp:Button ID="btn_store" runat="server" Text="Store To Database" BackColor="#41B7D8" ForeColor="White" Font-Bold="true" OnClick="btn_store_Click" BorderStyle="None" Height="32px" /></td>
                </tr>
            </table>
        </center>
    </form>
</body>
</html>

Code Behind in C#:-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Data.OleDb;
using System.Data;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
    
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void btnUpload_Click(object sender, EventArgs e)
    {
        string connectionString = "";
        if (FileUpload1.HasFile)
        {
            DataTable dtExcelRecords = new DataTable();
            string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
            string fileExtension = Path.GetExtension(FileUpload1.PostedFile.FileName);
            string fileLocation = Server.MapPath("~/App_Data/" + fileName);
            FileUpload1.SaveAs(fileLocation);

            //Check whether file extension is xls or xslx

            if (fileExtension == ".xls")
            {
                connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileLocation + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
            }
            else if (fileExtension == ".xlsx")
            {
                connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileLocation + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
            }

            //Create OleDB Connection and OleDb Command

            OleDbConnection con = new OleDbConnection(connectionString);
            OleDbCommand cmd = new OleDbCommand();
            cmd.CommandType = System.Data.CommandType.Text;
            cmd.Connection = con;
            OleDbDataAdapter dAdapter = new OleDbDataAdapter(cmd);

            con.Open();
            DataTable dtExcelSheetName = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
            string getExcelSheetName = dtExcelSheetName.Rows[0]["Table_Name"].ToString();
            cmd.CommandText = "SELECT * FROM [" + getExcelSheetName + "]";
            dAdapter.SelectCommand = cmd;
            dAdapter.Fill(dtExcelRecords);
            Session["sdt"] = dtExcelRecords;
            con.Close();
            GridView1.DataSource = dtExcelRecords;
            GridView1.DataBind();

        }
    }
    protected void btn_store_Click(object sender, EventArgs e)
    {
        String conStr = "Data Source=SQLDB;Initial Catalog=Demo;Persist Security Info=True;User ID=Demoh;Password=Demo1@";


        SqlConnection con = new SqlConnection(conStr);
        con.Open();
        SqlBulkCopy sqlBulk = new SqlBulkCopy(con);

        DataTable dt = new DataTable();
        dt = (DataTable)Session["sdt"];

        //Give your Destination table name

        sqlBulk.DestinationTableName = "aby_temp";
        
        //map the columns if you have differant no.of columns in Destination 

        sqlBulk.ColumnMappings.Add("fname", "fname");
        sqlBulk.ColumnMappings.Add("category","category");
        sqlBulk.WriteToServer(dt);

        con.Close();
    }
}


Read More

Friday, July 19, 2013

Export Data from Gridview to Excel File in Asp.net C# with Example

3 comments :

Hello Friends, here in this post we will learn How to Export data from  gridview to Excel file. It is good to provide data in excel sheet. when your web application's data driven means allows user to export data from application for a record than Excel is best option because it is very popular and all users have knowledge of excel so He/She can manage data in their way.


In the following example we will use Render Control method providing content of server control. This method will confirms that an HTML Form control is rendered for the specified Asp.Net server control at run time.

 Screen shot of following application:-





When you click on "Export To Excel" Button it will ask for Download option "Open With" or "Save As". Choose Open with option it will open Excel sheet with gridview data like bellow.....




Source Code in (ASP.net):-

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="GridToExcel.aspx.cs" Inherits="BlogCodeTester.GridToXml" %>

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:GridView ID="gvData" runat="server" AutoGenerateColumns="False" BackColor="White" BorderColor="#DEDFDE" BorderStyle="None" BorderWidth="1px" CellPadding="4" ForeColor="Black" GridLines="Vertical">
                <AlternatingRowStyle BackColor="White" />
                <Columns>
                    <asp:TemplateField HeaderText="Name">
                        <ItemTemplate>
                            <asp:Label ID="lblnm" runat="server" Text='<%#Eval("fname")%>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Category">
                        <ItemTemplate>
                            <asp:Label ID="lblnm" runat="server" Text='<%#Eval("category")%>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                </Columns>
                <FooterStyle BackColor="White" />
                <HeaderStyle BackColor="#43C0EE" Font-Bold="True" ForeColor="White" />
                <RowStyle BackColor="#C5DFEE" />
            </asp:GridView>
            <asp:Button ID="btn_exporttoecel" runat="server" OnClick="btn_exporttoecel_Click" Text="Export To  Excel" />
        </div>
    </form>
</body>
</html>

Code in C#:-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

namespace BlogCodeTester
{
    public partial class GridToXml : System.Web.UI.Page
    {
        DataClasses1DataContext dc = new DataClasses1DataContext();
        protected void Page_Load(object sender, EventArgs e)
        {
            gvData.DataSource = from a in dc.aby_temps select a;
            gvData.DataBind();
        }

        protected void btn_exporttoecel_Click(object sender, EventArgs e)
        {
            Response.ClearContent();
            Response.Buffer = true;
            Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "DataFromGrid.xls"));

            // given file name is "DataFromGrid" you can give as you want

            Response.ContentType = "application/ms-excel";
            StringWriter stringWrite = new StringWriter();
            HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);

            gvData.RenderControl(htmlWrite);
            Response.Write(stringWrite.ToString());
            Response.End();
        }
        public override void VerifyRenderingInServerForm(Control control)
        {
            // Confirms that an HtmlForm control is rendered for the
        }

    }
}

Read More

Wednesday, July 3, 2013

How to Store and Retrieve Images from Database and Display in Gridview in ASP.NET with C# - Example

No comments :

Introduction:

Here in this post I explain how to store and retrieve images from database and also display images in gridview.

In this example i have used simple form in which your can upload his image using Fileupload control. this uploaded image is stored in to the project directory and the path of a directory with file name is stored into database. when  we bind gridview this path will be assigned to image control.

here is the image of form

Database Table:-

Source Code(in asp.net):-

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="GridViewwithoutRowCmd.aspx.cs" Inherits="_Default" %>

<!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 runat="server">
    <title></title>
    <style type="text/css">
        .auto-style1 {
            width: 100%;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <br />
        <asp:HiddenField ID="hid" runat="server" />
        <center>         
             <table class="auto-style1">
              <tr>
                  <td align="center">
        <asp:Literal ID="Literal1" runat="server" Text="Name"></asp:Literal>
                  </td>
                  <td align="left">
        <asp:TextBox ID="tname" runat="server"></asp:TextBox>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" 
            ControlToValidate="tname" ErrorMessage="RequiredFieldValidator" 
            ValidationGroup="vreg"></asp:RequiredFieldValidator>
                  </td>
              </tr>
              <tr>
                  <td align="center">
        <asp:Literal ID="Literal2" runat="server" Text="Gender"></asp:Literal>
                  </td>
                  <td align="left">
        <asp:RadioButtonList ID="RadioButtonList1" runat="server" Height="16px" 
            RepeatDirection="Horizontal" Width="60px">
            <asp:ListItem Value="0">MALE</asp:ListItem>
            <asp:ListItem Value="1">FEMALE</asp:ListItem>
        </asp:RadioButtonList>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" 
            ControlToValidate="RadioButtonList1" ErrorMessage="RequiredFieldValidator" 
            ValidationGroup="vreg"></asp:RequiredFieldValidator>
                  </td>
              </tr>
              <tr>
                  <td align="center">
        <asp:Literal ID="Literal5" runat="server" Text="Image URL"></asp:Literal>
                  </td>
                  <td align="left">
        <asp:FileUpload ID="ImageUpload" runat="server" />
        <asp:RequiredFieldValidator ID="RequiredFieldValidator5" runat="server" 
            ControlToValidate="ImageUpload" ErrorMessage="RequiredFieldValidator" 
            ValidationGroup="vreg"></asp:RequiredFieldValidator>
                  </td>
              </tr>
              <tr>
                  <td align="center">&nbsp;</td>
                  <td align="left">
    
        <asp:Button ID="badd" runat="server" Text="Add" onclick="badd_Click" 
            ValidationGroup="vreg"/>
    
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <asp:Button ID="bcancle" runat="server" Text="Cancle" onclick="bcancle_Click" />
    
                  </td>
              </tr>
              <tr>
                  <td colspan="2" align="center">
          <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
            CellPadding="4" ForeColor="#333333" 
            GridLines="None">
        <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
        <Columns>
             <asp:TemplateField HeaderText="id" Visible="false">
            <ItemTemplate>
                 <asp:Label ID="lid" runat="server" Text='<% #Eval("id")%>'></asp:Label>
            </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Name">
            <ItemTemplate>
                 <asp:Label ID="lname" runat="server" Text='<% #Eval("name")%>'></asp:Label>
            </ItemTemplate>
            </asp:TemplateField>
           
             <asp:TemplateField HeaderText="Gender">
            <ItemTemplate>
                      <asp:Label ID="lgender" runat="server" Text='<%# Eval("gender").ToString()=="0" ? "MALE":"FEMALE" %>'></asp:Label>
            </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Image">
                <ItemTemplate>
                    <asp:Image ID="Image1" runat="server" Height="200px" Width="200px" ImageUrl='<%#Eval("image") %>'/>
                </ItemTemplate>
            </asp:TemplateField>
             <asp:TemplateField>
                <ItemTemplate>
                    <asp:LinkButton ID="lbedit" runat="server" OnClick="editDetail">Edit</asp:LinkButton>
                    
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField>
            <ItemTemplate>
                <asp:LinkButton ID="lbdelete" runat="server" OnClick="deleteDetail">Delete</asp:LinkButton>
            </ItemTemplate>
            </asp:TemplateField>
            
        </Columns>
        <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
        <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
        <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
        <HeaderStyle BackColor="#090A0A" Font-Bold="True" ForeColor="White" />
        <EditRowStyle BackColor="#999999" />
        <AlternatingRowStyle BackColor="White" ForeColor="#0B0B0C" />
        </asp:GridView>
                  </td>
              </tr>
        </table>
        </center>


            
    </div>
    </form>
</body>
</html>

Code behind(in C#):-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page 
{
    static string str = @"Data Source=SQLDB;Persist Security Info=True;User ID=Demoh;Password=Demo1@";
    public static SqlConnection con = new SqlConnection(str);
    DataTable dtTemp = new DataTable();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            GridView1.DataSource = Data_of_Grid("select * from aby_GridviewWithoutRowCmd");
            GridView1.DataBind();
        }
    }

 protected void badd_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            if (badd.Text == "Add")
            {
                string ig = ImageUpload.FileName.ToString();
                    string url = "photo/" + ig;
                    ImageUpload.SaveAs(Server.MapPath("~//") + url);//this function will store the image in to you project

                Cmd_Non_Query("INSERT INTO aby_GridviewWithoutRowCmd(name,gender,image) VALUES ('" + tname.Text + "'," + RadioButtonList1.SelectedValue + ",'" + url + "')");
            }
            else
            {

                int i = Convert.ToInt32(hid.Value);
              
                string ig = ImageUpload.FileName.ToString();
                string url = "photo/" + ig;
                ImageUpload.SaveAs(Server.MapPath("~//") + url);
              
                if (Cmd_Scaler("select id from aby_GridviewWithoutRowCmd where id=" + hid.Value) != null)
                {
                    Cmd_Non_Query("UPDATE aby_GridviewWithoutRowCmd set name='" + tname.Text + "', gender=" + RadioButtonList1.SelectedValue + ", image='" + url + "' where id=" + hid.Value.ToString());
                }
                badd.Text = "Add";
            }

            GridView1.DataSource = Data_of_Grid("select * from aby_GridviewWithoutRowCmd");
            GridView1.DataBind();
        }
        clr();
    }
 protected void editDetail(object sender, EventArgs e)
 {

     LinkButton lb = (LinkButton)sender;
     GridViewRow gr = lb.NamingContainer as GridViewRow;

     Label lid1 = (Label)gr.FindControl("lid");
     hid.Value = lid1.Text;      //store the id of record into hiddenfield used when we actully submit changes 

     Label lname1 = (Label)gr.FindControl("lname");
     tname.Text = lname1.Text;

     Label lgender1 = (Label)gr.FindControl("lgender");
     RadioButtonList1.SelectedValue = RadioButtonList1.Items.FindByText(lgender1.Text).Value;

     Image im = (Image)gr.FindControl("Image1");


     badd.Text = "Update";
 }
 protected void deleteDetail(object sender, EventArgs e)
 {
     badd.Text = "Add";
     LinkButton lb = (LinkButton)sender;
     GridViewRow gr = lb.NamingContainer as GridViewRow;
     Image im = (Image)gr.FindControl("Image1");

     System.IO.File.Delete(Server.MapPath(im.ImageUrl));

     Label lid1 = (Label)gr.FindControl("lid");
     Cmd_Non_Query("delete from aby_GridviewWithoutRowCmd where id=" + lid1.Text);

     GridView1.DataSource = Data_of_Grid("select * from aby_GridviewWithoutRowCmd");
     GridView1.DataBind();
 }

public void clr()
    {
        tname.Text = "";
        RadioButtonList1.SelectedIndex = -1;
      
    }
    public void bcancle_Click(object sender, EventArgs e)
    {
        badd.Text = "Add";
        clr();
    }
    //functions for Database operations
    public DataTable Data_of_Grid(string q)
    {
        DataTable dt = new DataTable();
        try
        {
            if (con.State == ConnectionState.Closed)
            {
                con.Open();
            }
            SqlCommand cmd = new SqlCommand(q, con);
            SqlDataAdapter sd = new SqlDataAdapter();
            sd.SelectCommand = cmd;
            sd.Fill(dt);

        }
        catch (Exception err)
        {
            //TODO
        }
        finally
        {
            con.Close();
        }
        return dt;
    }
    public void Cmd_Non_Query(string q)
    {
        try
        {
            SqlCommand cmd = new SqlCommand(q, con);
            if (con.State == ConnectionState.Closed)
            {
                con.Open();
            }
            cmd.ExecuteNonQuery();
        }
        catch (Exception err)
        {
        }
        finally
        {
            con.Close();
        }

    }
    public Object Cmd_Scaler(string q)
    {
        if (con.State == ConnectionState.Closed)
        {
            con.Open();
        }

        SqlCommand cmd = new SqlCommand(q, con);
        string val = string.Empty;
        return cmd.ExecuteScalar();
        con.Close();

    }

 
}

Read More

Saturday, June 8, 2013

Insert, Update, Delete in Database through GridView using ModalPopupExtender control of Ajax in ASP.NET with C# - Example

2 comments :

Introduction:-

Insert, Update, Delete in Database through GridView using ModalPopupExtender control of Ajax in ASP.NET with C# - Example
Introduction:-
              Here I want to provide Insert, Update and Delete Operation in Gridview using ModelPopupExtender Control of Ajax Toolkit 3.0.
when you click on "Edit" link button or "Insert" Button The Popup Window will Open which has proper controls to edit or insert data.
In this case I got requirement to create a gridview with edit and insert operation when user click on edit or insert link button it displays one popup in that popup I have provided interface to edit or insert new record.

To implement this requirement I had created one panel in which I had provided two textboxes to insert or edit data and two buttons to submit changes or cancel. I had given this panel’s id in popup control of ModelPopupExtender.

            


Source Code(in asp.net):-


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Popup.aspx.cs" Inherits="Popup" %>

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<!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">
    <title></title>
    <style type="text/css">
        .ModalPopupBG
        {
            background-color: #C0C0C0;
            filter: alpha(opacity=50);
            opacity: 0.7;
        }
        .DetailPopup
        {
            min-width: 200px;
            min-height: 150px;
            background: white;
        }
        .detailpopup1
        {
            font-size: larger;
            font-weight: bold;
            font-style: normal;
            color: #000000;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
    </asp:ToolkitScriptManager>
    <asp:HiddenField ID="hid" runat="server" />
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4"
        ForeColor="#333333" GridLines="None">
        <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
        <Columns>
            <asp:TemplateField HeaderText="Pid">
                <ItemTemplate>
                    <asp:Label ID="lpid" runat="server" Text='<% #Eval("pid")%>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Name">
                <ItemTemplate>
                    <asp:Label ID="lpname" runat="server" Text='<% #Eval("pname")%>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Description">
                <ItemTemplate>
                    <asp:Label ID="ldes" runat="server" Text='<% #Eval("des")%>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField>
                <ItemTemplate>
                    <asp:LinkButton ID="lbedit" runat="server" OnClick="lbedit_Click">Edit</asp:LinkButton>
                    &nbsp;<asp:LinkButton ID="lbdel" runat="server" OnClick="lbdel_Click">Delete</asp:LinkButton>
                    &nbsp;
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
        <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
        <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
        <EditRowStyle BackColor="#999999" />
        <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
    </asp:GridView>
    <asp:Button ID="bntinsert" runat="server" Text="Insert" OnClick="bntinsert_Click" />
    <asp:ModalPopupExtender ID="ModalPopupExtender1" runat="server" TargetControlID="hid"
        PopupControlID="pan" BehaviorID="bntinsert_Click" PopupDragHandleControlID="PopupHeader"
        Drag="true" BackgroundCssClass="ModalPopupBG">
    </asp:ModalPopupExtender>
    <asp:Panel runat="server" ID="pan">
        <table class="DetailPopup">
            <tr>
                <td colspan="2">
                    <h1>
                        <asp:Label ID="lpopuphead" runat="server" Text=""></asp:Label></h1>
                </td>
            </tr>
            <tr>
                <td>
                    Product Name:-
                </td>
                <td>
                    <asp:TextBox ID="txtpnm" runat="server"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="Plz Enter Product Name"
                        ControlToValidate="txtpnm" ValidationGroup="vpopup"></asp:RequiredFieldValidator>
                </td>
            </tr>
            <tr>
                <td>
                    Product Description:-
                </td>
                <td>
                    <asp:TextBox ID="txtpdes" runat="server"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="Plz Enter Description"
                        ControlToValidate="txtpdes" ValidationGroup="vpopup"></asp:RequiredFieldValidator>
                </td>
            </tr>
            <tr>
                <td>
                    <asp:Button ID="btnOkay" runat="server" Text="OK" OnClick="btnOkay_Click" ValidationGroup="vpopup" />
                    <asp:Button ID="btnCncle" runat="server" Text="CANCLE" OnClick="btnCncle_Click" />
                </td>
            </tr>
        </table>
    </asp:Panel>
    </form>
</body>
</html>



 Codebehind(in C#):-



using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Popup : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            grbind();
        }
    }

    protected void grbind()
    {
        GridView1.DataSource = Data_of_Grid("select * from aby_Productnew");
        GridView1.DataBind();
    }
    protected void lbedit_Click(object sender, EventArgs e)
    {
        LinkButton lb = (LinkButton)sender;
        GridViewRow gr = (GridViewRow)lb.NamingContainer;

        Label lpid1 = (Label)gr.FindControl("lpid");
        hid.Value = lpid1.Text;

        Label lpname1 = (Label)gr.FindControl("lpname");
        txtpnm.Text = lpname1.Text;

        Label ldes1 = (Label)gr.FindControl("ldes");
        txtpdes.Text = ldes1.Text;

        lpopuphead.Text = "Edit Record";
        ModalPopupExtender1.Show();

    }

    protected void lbdel_Click(object sender, EventArgs e)
    {
        LinkButton lb = (LinkButton)sender;
        GridViewRow gr = (GridViewRow)lb.NamingContainer;
        Label lpid1 = (Label)gr.FindControl("lpid");
        Cmd_Non_Query("delete from aby_Productnew where pid=" + lpid1.Text);
        grbind();
    }

    protected void btnOkay_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            if (lpopuphead.Text.Equals("Edit Record"))
            {
                Cmd_Non_Query("update aby_Productnew set pname='" + txtpnm.Text + "', des='" + txtpdes.Text + "' where pid=" + hid.Value);
            }
            else
            {
                Cmd_Non_Query("insert into aby_Productnew values('" + txtpnm.Text + "','" + txtpdes.Text + "')");
            }
            grbind();
        }
        clr();
   }

    private void clr()
    {
        lpopuphead.Text = "";
        txtpdes.Text = "";
        txtpnm.Text = "";
    }

    protected void bntinsert_Click(object sender, EventArgs e)
    {
        lpopuphead.Text = "Insert Record";
        ModalPopupExtender1.Show();
    }

    protected void btnCncle_Click(object sender, EventArgs e)
    {
        clr();
        ModalPopupExtender1.Hide();
    }

    public DataTable Data_of_Grid(string q)
    {
        DataTable dt = new DataTable();
        try
        {
           if (con.State == ConnectionState.Closed)
            {
               con.Open();
            }
            SqlCommand cmd = new SqlCommand(q, con);
            SqlDataAdapter sd = new SqlDataAdapter();
            sd.SelectCommand = cmd;
            sd.Fill(dt);
        }
        catch (Exception err)
        {
            //TODO
        }
        finally
        {
            con.Close();
        }
        return dt;
    }

    public void Cmd_Non_Query(string q)
    {
        try
        {
            SqlCommand cmd = new SqlCommand(q, con);
            if (con.State == ConnectionState.Closed)
            {
                con.Open();
            }
            cmd.ExecuteNonQuery();
        }
        catch (Exception err)
        {
        }
        finally
        {
            con.Close();
        }
    }
}

Read More

Friday, May 24, 2013

Gridview with Pagefooter per Page total and grand total are displayed in PageFooter in Asp.net with C# - Example

1 comment :

 Introduction:

In this Post I will explain how to Display total of any numeric column in gridview pagefooter, and also display Grand total.

In this case I got requirement to display per page total of numeric column as well as grand total for all records. It means that you have to calculate page total for each page and also calculate grand total of all records at every page so we can put it on pagefooter of grid view

To implement this requirement I had created OnRowDataBound event of gridview to calculate per page total and also for grand total.
Note:-
    In this example I use inner join queries because I am taking data from two different tables with using sql sum() function and Groupby clause. If you have single table you can avoid it. Don’t forgot to replace connection string with your database connection string.


Source Code(in asp.net)

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ProductView2.aspx.cs" Inherits="ProductView" %>

<!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 runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4"
            ForeColor="#333333" GridLines="None" DataKeyNames="pid" OnRowDataBound="GridView1_RowDataBound"
            ShowFooter="True" AllowPaging="True" OnPageIndexChanging="GridView1_PageIndexChanging"
            PageSize="3">
            <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
            <Columns>
                <asp:TemplateField HeaderText="Pid" Visible="false">
                    <ItemTemplate>
                        <asp:Label ID="lpid" runat="server" Text='<% #Eval("pid")%>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Name">
                    <ItemTemplate>
                        <asp:Label ID="lpname" runat="server" Text='<% #Eval("pname")%>'></asp:Label>
                    </ItemTemplate>
                    <FooterTemplate>
                        Grand Total:-
                        <asp:Label ID="lblgrt" runat="server"></asp:Label></FooterTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Description">
                    <ItemTemplate>
                        <asp:Label ID="ldes" runat="server" Text='<% #Eval("des")%>'></asp:Label>
                    </ItemTemplate>
                    <FooterTemplate>
                        Page Total:-</FooterTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Total">
                    <ItemTemplate>
                        <asp:Label ID="ltotal" runat="server" Text='<% #Eval("EXpr1")%>'></asp:Label>
                    </ItemTemplate>
                    <FooterTemplate>
                        <asp:Label ID="lgtotal" runat="server" Text="Label"></asp:Label>
                    </FooterTemplate>
                </asp:TemplateField>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:LinkButton ID="lbdelete" runat="server" OnClick="deleteDetail" CommandArgument='<% #Eval("pid")%>'>Delete</asp:LinkButton>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
            <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
            <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
            <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <EditRowStyle BackColor="#999999" />
            <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
        </asp:GridView>
        Grand Total:-
        <asp:Label ID="lb" runat="server"></asp:Label>
        <br />
    </div>
    </form>
</body>
</html>

Code Behind(in C#)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
public partial class ProductView : System.Web.UI.Page
{
    static string str = @"Yor Conection string";
    public static SqlConnection con = new SqlConnection(str);
    decimal tot,gt;
   
    //events
    protected void Page_Load(object sender, EventArgs e)
    {               
        if (!IsPostBack)
        {
            DataTable dt = Data_of_Grid("SELECT aby_Productnew.pname, aby_Productnew.des, aby_ProductRate.pid, SUM(aby_ProductRate.total) AS Expr1 FROM aby_ProductRate INNER JOIN aby_Productnew ON aby_ProductRate.pid = aby_Productnew.pid GROUP BY aby_ProductRate.pid, aby_Productnew.pname, aby_Productnew.des");
           
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                gt += Convert.ToDecimal(dt.Rows[i][3]);

            }
            tot = 0;
            GridView1.DataSource = Data_of_Grid("SELECT aby_Productnew.pname, aby_Productnew.des, aby_ProductRate.pid, SUM(aby_ProductRate.total) AS Expr1 FROM aby_ProductRate INNER JOIN aby_Productnew ON aby_ProductRate.pid = aby_Productnew.pid GROUP BY aby_ProductRate.pid, aby_Productnew.pname, aby_Productnew.des");
            GridView1.DataBind();
           
           lb.Text = gt.ToString();
         
        }
        
       
    }
    protected void deleteDetail(object sender, EventArgs e)
    {
        LinkButton lb = (LinkButton)sender;
        Cmd_Non_Query("delete from aby_Productnew where pid='" + lb.CommandArgument+"'");
        GridView1.DataSource = Data_of_Grid("SELECT aby_Productnew.pname, aby_Productnew.des, aby_ProductRate.pid, SUM(aby_ProductRate.total) AS Expr1 FROM aby_ProductRate INNER JOIN aby_Productnew ON aby_ProductRate.pid = aby_Productnew.pid GROUP BY aby_ProductRate.pid, aby_Productnew.pname, aby_Productnew.des");
        GridView1.DataBind();
    }
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Control ctr = e.Row.FindControl("ltotal");
            if (ctr != null)
            {
                Label l = (Label)ctr;
                tot += Convert.ToDecimal(l.Text);
              
            }
        }
        if (e.Row.RowType == DataControlRowType.Footer)
        {
            Label lbl = (Label)e.Row.FindControl("lblgrt");
            lbl.Text = Cmd_Scaler("SELECT SUM(aby_ProductRate.total) AS Expr1 FROM aby_ProductRate").ToString();
            Label lblamount = (Label)e.Row.FindControl("lgtotal");
            lblamount.Text = tot.ToString();
        }
      
    }

    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
        tot = 0;
        GridView1.DataSource = Data_of_Grid("SELECT aby_Productnew.pname, aby_Productnew.des, aby_ProductRate.pid, SUM(aby_ProductRate.total) AS Expr1 FROM aby_ProductRate INNER JOIN aby_Productnew ON aby_ProductRate.pid = aby_Productnew.pid GROUP BY aby_ProductRate.pid, aby_Productnew.pname, aby_Productnew.des");
        GridView1.DataBind();
    }
    
    //sql Function
    public DataTable Data_of_Grid(string q)
    {
        DataTable dt = new DataTable();
        try
        {
            if (con.State == ConnectionState.Closed)
            {
                con.Open();
            }
            SqlCommand cmd = new SqlCommand(q, con);
            SqlDataAdapter sd = new SqlDataAdapter();
            sd.SelectCommand = cmd;
            sd.Fill(dt);

        }
        catch (Exception err)
        {
            //TODO
        }
        finally
        {
            con.Close();
        }
        return dt;
    }
    public void Cmd_Non_Query(string q)
    {
        try
        {
            SqlCommand cmd = new SqlCommand(q, con);
            if (con.State == ConnectionState.Closed)
            {
                con.Open();
            }
            cmd.ExecuteNonQuery();
        }
        catch (Exception err)
        {
        }
        finally
        {
            con.Close();
        }

    }
    public Object Cmd_Scaler(string q)
    {
        if (con.State == ConnectionState.Closed)
        {
            con.Open();
        }
        SqlCommand cmd = new SqlCommand(q, con);
        string val = string.Empty;




        return cmd.ExecuteScalar();
        con.Close();

    }
}
Read More

Monday, May 13, 2013

Gridview with Detailsview in ModelPopupExtender in asp.net with c#-Example

No comments :

Introduction:-

In this example if i have multiple columns in Database Table but it looks massive in Gridview. so it is very useful example.
Detailsview is one of Data Control in asp.net, it is used to display information. here i have put the detailview in ModelPopupExtender which is Ajax Control. my logic behind this example is that i will display only important fields in gridview and rest of the fields are display when you click on View link button in Gridview when you. when you click link button it will display all the fields of selected records in grid view.


Source Code(in asp.net):-


<%@ page language="C#" autoeventwireup="true" codefile="GridWithDetailsView.aspx.cs"
    inherits="GridWithDetailsView" %>

<%@ register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="cc1" %>
<!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">
    <title></title>
    <style type="text/css">
        .ModalPopupBG
        {
            background-color: #C0C0C0;
            filter: alpha(opacity=50);
            opacity: 0.7;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <cc1:toolkitscriptmanager id="ToolkitScriptManager1" runat="server">
        </cc1:toolkitscriptmanager>
        <asp:gridview id="GridView1" runat="server" autogeneratecolumns="False" cellpadding="4"
            forecolor="#333333" gridlines="None">
            <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
            <Columns>
                <asp:TemplateField HeaderText="Pid">
                    <ItemTemplate>
                        <asp:Label ID="lpid" runat="server" Text='<% #Eval("pid")%>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Name">
                    <ItemTemplate>
                        <asp:Label ID="lpname" runat="server" Text='<% #Eval("pname")%>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Description">
                    <ItemTemplate>
                        <asp:Label ID="ldes" runat="server" Text='<% #Eval("des")%>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:LinkButton ID="lbview" runat="server" OnClick="lbview_Click" CommandArgument='<%#Eval("pid") %>'>View</asp:LinkButton>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
            <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
            <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <EditRowStyle BackColor="#999999" />
            <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
        </asp:gridview>
        <cc1:modalpopupextender id="ModalPopupExtender1" runat="server" popupcontrolid="PopupTable"
            targetcontrolid="HiddenField1" cancelcontrolid="btn_close" backgroundcssclass="ModalPopupBG">
        </cc1:modalpopupextender>
        <table id="PopupTable" style="display: none">
            <tr>
                <td>
                    <asp:button id="btn_close" runat="server" text="Close" />
                </td>
            </tr>
            <tr>
                <td>
                    <asp:detailsview id="DetailsView1" runat="server" height="50px" width="125px" autogeneraterows="False">
                        <Fields>
                            <asp:BoundField DataField="pid" HeaderText="Product Id" />
                            <asp:BoundField DataField="pname" HeaderText="Product Name" />
                            <asp:BoundField DataField="des" HeaderText="Product description" />
                        </Fields>
                    </asp:detailsview>
                </td>
            </tr>
        </table>
        <asp:hiddenfield id="HiddenField1" runat="server" />
        <%--it is not used it is just give id to model popup--%>
    </div>
    </form>
</body>
</html>


Code Behind(in C#):-


using System;
using System.Collections.Generic;
using System.Linq; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
public partial class GridWithDetailsView : System.Web.UI.Page 
{    
    DataClassesDataContext dc = new DataClassesDataContext();
    SqlFun.SqlFun sqlobj = new SqlFun.SqlFun();
   
    protected void Page_Load(object sender, EventArgs e)    
    {        
        if (!IsPostBack)        
        {            
            grbind();        
        }    
    }    
    protected void grbind()    
    {        
        GridView1.DataSource = dc.aby_Productnews;//this is my Linq object otherwise you ncan use select query        
        GridView1.DataBind();    
    }    
    protected void lbview_Click(object sender, EventArgs e)    
    {        
        LinkButton lb = (LinkButton)sender;        
        DetailsView1.DataSource = (from p in dc.aby_Productnews 
                                   where p.pid == Convert.ToInt32(lb.CommandArgument) select p).ToList();        
        DetailsView1.DataBind();        
        ModalPopupExtender1.Show();    
    } 
} 
Read More

Friday, April 5, 2013

Nested ModelPopupExtender with GridView in popup and Linq Query is used for Insert,Update Delete in asp.net with c#-Example

No comments :

Introduction:-

We all have used the ModalPopupExtender and know how it works. It displays a detail part as a model, which means we cannot interact with rest of the part of page except the detail part. But there is a problem in ModalPopupExtender.
When you try to display another ModalPopupExtender on the first one, it does not hide the first ModalPopupExtender. We can interact with the first ModalPopupExtender. Sometimes it spoils the application logic.

That’s why I am solving this problem by a User Control named UpdatePanel . It sets the child model popup on the parent model popup. You can add multiple UpdatePanel controls to set multiple relations between model pops. We can nest many model pop controls to any level.
Here In this Example I used the Nested ModelPopupExtender. In first popup Gridview is opened and for Insert and Update Operation Nested popup will open which has simple textboxes and buttons.

Note:
    - When you use ModelPopupExtender you have to put one button in ModelPopupExtender to close that model popup.
    - I am using Linq for Insert, Update, Delete operations on Database.


click The Button  First Popup Will Open

When you click on Edit Link Button or Insert Button then next Popup will open


Source Code(in asp.net):-


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Popup.aspx.cs" Inherits="Popup" %>

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<!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">
    <title></title>
    <style type="text/css">
        .ModalPopupBG
        {
            background-color: #C0C0C0;
            filter: alpha(opacity=50);
            opacity: 0.7;
        }
        .DetailPopup
        {
            min-width: 200px;
            min-height: 150px;
            background: white;
        }
        .detailpopup1
        {
            font-size: larger;
            font-weight: bold;
            font-style: normal;
            color: #000000;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
    </asp:ToolkitScriptManager>
    <asp:Button ID="btnMain" runat="server" Text="Click me to View" />
    <asp:ModalPopupExtender ID="ModalPopupExtender2" runat="server" TargetControlID="btnMain"
        PopupControlID="Mainpan" CancelControlID="btnMainCancle" Drag="true" BackgroundCssClass="ModalPopupBG">
    </asp:ModalPopupExtender>
    <asp:Panel ID="Mainpan" runat="server">
        <asp:UpdatePanel ID="updateParent" runat="Server">
            <ContentTemplate>
                <asp:HiddenField ID="hid" runat="server" />
                <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4"
                    ForeColor="#333333" GridLines="None">
                    <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
                    <Columns>
                        <asp:TemplateField HeaderText="Pid">
                            <ItemTemplate>
                                <asp:Label ID="lpid" runat="server" Text='<% #Eval("pid")%>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Name">
                            <ItemTemplate>
                                <asp:Label ID="lpname" runat="server" Text='<% #Eval("pname")%>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Description">
                            <ItemTemplate>
                                <asp:Label ID="ldes" runat="server" Text='<% #Eval("des")%>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField>
                            <ItemTemplate>
                                <asp:LinkButton ID="lbedit" runat="server" OnClick="lbedit_Click">Edit</asp:LinkButton>
                                &nbsp;<asp:LinkButton ID="lbdel" runat="server" OnClick="lbdel_Click">Delete</asp:LinkButton>
                                &nbsp;
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                    <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
                    <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                    <EditRowStyle BackColor="#999999" />
                    <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
                </asp:GridView>
                <asp:Button ID="bntinsert" runat="server" Text="Insert" OnClick="bntinsert_Click" />
                <asp:Button ID="btnMainCancle" runat="server" Text="Cancle" OnClick="btnMainCancle_Click" />
                <asp:ModalPopupExtender ID="ModalPopupExtender1" runat="server" TargetControlID="hid"
                    PopupControlID="pan" BehaviorID="bntinsert_Click" PopupDragHandleControlID="PopupHeader"
                    Drag="true" BackgroundCssClass="ModalPopupBG">
                </asp:ModalPopupExtender>
                <asp:Panel runat="server" ID="pan">
                    <table class="DetailPopup">
                        <tr>
                            <td colspan="2">
                                <h1>
                                    <asp:Label ID="lpopuphead" runat="server" Text=""></asp:Label></h1>
                            </td>
                        </tr>
                        <tr>
                            <td>
                                Product Name:-
                            </td>
                            <td>
                                <asp:TextBox ID="txtpnm" runat="server"></asp:TextBox>
                                <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="Plz Enter Product Name"
                                    ControlToValidate="txtpnm" ValidationGroup="vpopup"></asp:RequiredFieldValidator>
                            </td>
                        </tr>
                        <tr>
                            <td>
                                Product Description:-
                            </td>
                            <td>
                                <asp:TextBox ID="txtpdes" runat="server"></asp:TextBox>
                                <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="Plz Enter Description"
                                    ControlToValidate="txtpdes" ValidationGroup="vpopup"></asp:RequiredFieldValidator>
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <asp:Button ID="btnOkay" runat="server" Text="OK" OnClick="btnOkay_Click" ValidationGroup="vpopup" />
                                <asp:Button ID="btnCncle" runat="server" Text="CANCLE" OnClick="btnCncle_Click" />
                            </td>
                        </tr>
                    </table>
                </asp:Panel>
            </ContentTemplate>
        </asp:UpdatePanel>
    </asp:Panel>
    </form>
</body>
</html>

Code Behind(in C#):-


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Popup : System.Web.UI.Page
{
    DataClassesDataContext dc = new DataClassesDataContext();
    
    SqlFun.SqlFun sqlobj = new SqlFun.SqlFun();
    protected void Page_Load(object sender, EventArgs e)
    {
        if(!IsPostBack)
        {
            grbind();               
        }
    }
    protected void grbind()
    {
       
        GridView1.DataSource = dc.aby_Productnews;
        GridView1.DataBind();
    }
     
    protected void lbedit_Click(object sender, EventArgs e)
    {
        LinkButton lb=(LinkButton)sender;
        GridViewRow gr = (GridViewRow)lb.NamingContainer;
        

        Label lpid1 = (Label)gr.FindControl("lpid");
        hid.Value=lpid1.Text;
        Label lpname1 = (Label)gr.FindControl("lpname");
        txtpnm.Text = lpname1.Text;

        Label ldes1 = (Label)gr.FindControl("ldes");
        txtpdes.Text = ldes1.Text;


       lpopuphead.Text = "Edit Record";
        ModalPopupExtender1.Show();
        
    }
    protected void lbdel_Click(object sender, EventArgs e)
    {
        LinkButton lb = (LinkButton)sender;
        GridViewRow gr = (GridViewRow)lb.NamingContainer;

       Label lpid1 = (Label)gr.FindControl("lpid");

        //sqlobj.Cmd_Non_Query("delete from aby_Productnew where pid=" + lpid1.Text);
        grbind();
    
       
    }
    protected void btnOkay_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            if (lpopuphead.Text.Equals("Edit Record"))
            {
                aby_Productnew urec = dc.aby_Productnews.Single(u=>u.pid==Convert.ToInt32(hid.Value));
                urec.pname = txtpnm.Text;
                urec.des = txtpdes.Text;
                dc.SubmitChanges();

                //sqlobj.Cmd_Non_Query("update aby_Productnew set pname='" + txtpnm.Text + "', des='" + txtpdes.Text + "' where pid=" + hid.Value);
            }
            else
            {
                aby_Productnew abrec = new aby_Productnew();
               abrec.pname = txtpnm.Text;
                abrec.des = txtpdes.Text;
                dc.aby_Productnews.InsertOnSubmit(abrec);
                dc.SubmitChanges();
                //sqlobj.Cmd_Non_Query("insert into aby_Productnew values('" + txtpnm.Text + "','" + txtpdes.Text + "')");
            }
                grbind();
        }
        clr();
    }
    private void clr()
    {
        lpopuphead.Text = "";
        txtpdes.Text = "";
        txtpnm.Text = "";
    }
    protected void bntinsert_Click(object sender, EventArgs e)
    {
        lpopuphead.Text = "Insert Record";
        ModalPopupExtender1.Show();
    }
    protected void btnCncle_Click(object sender, EventArgs e)
    {
        clr();
        ModalPopupExtender1.Hide();        
    }
    protected void btnMainCancle_Click(object sender, EventArgs e)
    {
        ModalPopupExtender2.Hide();
    }

}
Read More

Thursday, March 14, 2013

Insert, Update, Delete operation in Database using Stored Procedure for controles like Radio Button, FileUplod , CheckBox and DropDownList in Gridview in asp.net with c#- Example

3 comments :

Introduction about Stored Procedure:-


                             A stored procedure is a group of sql statements that has been created and stored in the database. Stored procedure will accept input parameters so that a single procedure can be used over the network by several clients using different input data. Stored procedure will reduce network traffic and increase the performance. If we modify stored procedure all the clients will get the updated stored procedure.

My Procedure:-

 CREATE PROCEDURE [dbo].[AbyProc]
  (

    @nm nvarchar(50)=null,
    @gen nvarchar(50)=null,
    @quly bit=null,
    @post nvarchar(50)=null,
    @resume nvarchar(50)=null,
   
    @id int = null
  )

AS  
If @id IS NULL

    Begin
        insert into aby_JobApplication(nm,gen,quly,post,resume) values(@nm, @gen, @quly, @post, @resume)
    End

Else
    if @nm IS NOT NULL
        begin
            update aby_JobApplication set nm=@nm, gen=@gen, quly=@quly, post=@post, resume=@resume where id=@id
        End
    else
        Begin
            delete from aby_JobApplication where id=@id
        End





Source Code :-(in ASP.NET)


<%@ page language="C#" autoeventwireup="true" codefile="Proc.aspx.cs" inherits="Proc" %>

<!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 runat="server">
    <title></title>
    <style type="text/css">
        .style1
        {
            width: 100%;
        }
        .style2
        {
            width: 129px;
        }
        .style3
        {
            width: 129px;
            height: 26px;
        }
        .style4
        {
            height: 26px;
        }
        .style5
        {
            width: 129px;
            height: 56px;
        }
        .style6
        {
            height: 56px;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <table class="style1">
        <tr>
            <td class="style3">
                Name
            </td>
            <td class="style4">
                <asp:textbox id="txtnm" runat="server" maxlength="40"></asp:textbox>
                <asp:requiredfieldvalidator id="RequiredFieldValidator1" runat="server" controltovalidate="txtnm"
                    errormessage="RequiredFieldValidator" validationgroup="vjobapp"></asp:requiredfieldvalidator>
            </td>
        </tr>
        <tr>
            <td class="style5">
                gender
            </td>
            <td class="style6">
                <asp:radiobuttonlist id="rblgen" runat="server" height="39px" width="131px">

                    <asp:ListItem Selected="True" Value="0">MALE</asp:ListItem>
                    <asp:ListItem Value="1">FEMALE</asp:ListItem>
                </asp:radiobuttonlist>
           </td>
        </tr>
        <tr>
            <td class="style2">
                Qualification
            </td>
            <td>
                <asp:checkboxlist id="cbquly" runat="server">
                    <asp:ListItem>Deploma</asp:ListItem>
                    <asp:ListItem>Becholar</asp:ListItem>
                    <asp:ListItem>Post Gradute</asp:ListItem>
                </asp:checkboxlist>
            </td>
        </tr>
        <tr>
            <td class="style2">
                Appied For Post
            </td>
            <td>
                <asp:dropdownlist id="ddlpost" runat="server">
                    <asp:ListItem Value="0">&lt;SELECT POST&gt;</asp:ListItem>
                    <asp:ListItem>Project Manager</asp:ListItem>
                    <asp:ListItem>Tester</asp:ListItem>
                    <asp:ListItem>Developer</asp:ListItem>
                    <asp:ListItem>HR</asp:ListItem>
                    <asp:ListItem>System Support</asp:ListItem>
                </asp:dropdownlist>
                <asp:requiredfieldvalidator id="RequiredFieldValidator3" runat="server" controltovalidate="ddlpost"
                    errormessage="RequiredFieldValidator" initialvalue="0" validationgroup="vjobapp"></asp:requiredfieldvalidator>
            </td>
        </tr>
        <tr>
            <td class="style2">
                Image
            </td>
            <td>
                <asp:fileupload id="FileUplodResume" runat="server" />
                <asp:label id="lblpath" runat="server" visible="False"></asp:label>
                <asp:requiredfieldvalidator id="RequiredFieldValidator4" runat="server" controltovalidate="FileUplodResume"
                    errormessage="RequiredFieldValidator" validationgroup="vjobapp"></asp:requiredfieldvalidator>
            </td>
        </tr>
        <tr>
            <td class="style2">
                &nbsp;
            </td>
            <td>
                <asp:button id="btnadd" runat="server" onclick="btnAdd_Click" text="Add" validationgroup="vjobapp" />
                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                <asp:button id="btnCancle" runat="server" text="Cancle" onclick="btnCancle_Click" />
                <asp:hiddenfield id="hid" runat="server" />
            </td>
        </tr>
        <tr>
            <td class="style2">
            </td>
            <td>
                <asp:gridview id="GridView1" runat="server" autogeneratecolumns="False" cellpadding="4"
                    forecolor="#333333" gridlines="None">
                    <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />

                   <Columns>
                       <asp:TemplateField Visible="false">
                            <ItemTemplate>
                                <asp:Label ID="lid" runat="server" Text='<%#Eval("id")%>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Name">
                            <ItemTemplate>
                                <asp:Label ID="lnm" runat="server" Text='<%#Eval("nm")%>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Gender">
                            <ItemTemplate>
                                <asp:Label ID="lgen" runat="server" Text='<%# Eval("gen").ToString()=="0" ? "MALE":"FEMAlE" %>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Qualification">
                            <ItemTemplate>
                                <asp:Label ID="lquly" runat="server" Text='<%# Eval("quly")%>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                      
                         <asp:TemplateField HeaderText="Post">
                            <ItemTemplate>
                                <asp:Label ID="lpost" runat="server" Text='<%#Eval("post")%>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Name">
                            <ItemTemplate>
                              
                                <asp:Image ID="lresume" runat="server" Height="200px" Width="200px" ImageUrl='<%#Eval("resume") %>'/>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField>
                            <ItemTemplate>
                                <asp:LinkButton ID="lbedit" runat="server" OnClick="editDetail"
                                    CommandArgument='<% #Eval("id")%>'>Edit</asp:LinkButton>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField>
                            <ItemTemplate>
                                <asp:LinkButton ID="lbdelete" runat="server" OnClick="deleteDetail" CommandArgument='<% #Eval("id")%>'>Delete</asp:LinkButton>
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                    <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                    <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
                    <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
                    <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                    <EditRowStyle BackColor="#999999" />
                    <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
                </asp:gridview>
           </td>
       </tr>
    </table>
    </form>
</body>
</html>


Code Behind (in C#):-


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
public partial class Proc : System.Web.UI.Page
{
      static string str = @"Data Source=SQLDB;Persist Security Info=True;User ID=Demod;Password=Demo1@";
        public static SqlConnection con = new SqlConnection(str);
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                gridbind();
            }
        }
        private void gridbind()
        {
            GridView1.DataSource = Data_of_Grid("select * from aby_JobApplication");
            GridView1.DataBind();
        }
        public DataTable Data_of_Grid(string q)
        {
            DataTable dt = new DataTable();
            try
            {
                if (con.State == ConnectionState.Closed)
                {
                    con.Open();
                }
                SqlCommand cmd = new SqlCommand(q, con);
                SqlDataAdapter sd = new SqlDataAdapter();
                sd.SelectCommand = cmd;
                sd.Fill(dt);

            }
            catch (Exception err)
            {
                //TODO
            }
            finally
            {
                con.Close();
            }
            return dt;
        }
        protected void btnAdd_Click(object sender, EventArgs e)
        {
            string cbl = "";
            foreach (ListItem li in cbquly.Items)
            {
                if (li.Selected == true)
                {
                    cbl += li.Text + ",";
                }
            }

            string ig = FileUplodResume.FileName.ToString();
            string url = "photo/" + ig;
            FileUplodResume.SaveAs(Server.MapPath("~//") + url);
            SqlCommand command = new SqlCommand("[AbyProc]", con);
            command.CommandType = CommandType.StoredProcedure;
            command.Parameters.AddWithValue("@nm", txtnm.Text);
            command.Parameters.AddWithValue("@gen", rblgen.SelectedValue);
            command.Parameters.AddWithValue("@quly", cbl);
            command.Parameters.AddWithValue("@post", ddlpost.SelectedItem.Text);
            command.Parameters.AddWithValue("@resume", url);
            if (btnadd.Text == "Add")
            {
                //command.Parameters.AddWithValue("@id", null);
                if (con.State == ConnectionState.Closed)
                {
                    con.Open();
                }
                command.ExecuteNonQuery();
                con.Close();
            }
            else
            {
                command.Parameters.AddWithValue("@id", Convert.ToInt32(hid.Value));
                if (con.State == ConnectionState.Closed)
                {
                    con.Open();
                }
                command.ExecuteNonQuery();
                con.Close();
                btnadd.Text = "Add";
                lblpath.Visible = false;
            }
            clr();
            gridbind();
        }
        protected void editDetail(object sender, EventArgs e)
        {
            LinkButton lb = (LinkButton)sender;
            GridViewRow gr = (GridViewRow)lb.NamingContainer;
            hid.Value = lb.CommandArgument;
            Label lnm1 = (Label)gr.FindControl("lnm");
            txtnm.Text = lnm1.Text;
            Label lgen1 = (Label)gr.FindControl("lgen");
            rblgen.SelectedValue = lgen1.Text == "MALE" ? "0" : "1";
            Label lquly1 = (Label)gr.FindControl("lquly");
            foreach (ListItem li in cbquly.Items)
            {
                if (lquly1.Text.Contains(li.Text))
                {
                    li.Selected = true;
                }
            }

            //cbquly.Checked = lquly1.Text == "POST GRADUATED" ? true : false;
            Label lpost1 = (Label)gr.FindControl("lpost");
            ddlpost.SelectedValue = lpost1.Text;
            Image im = (Image)gr.FindControl("lresume");
            lblpath.Text = im.ImageUrl;
            lblpath.Visible = true;
            gridbind();
            btnadd.Text = "Update";
        }
        protected void deleteDetail(object sender, EventArgs e)
        {
            LinkButton lb = (LinkButton)sender;
            SqlCommand command = new SqlCommand("[AbyProc]", con);
            command.CommandType = CommandType.StoredProcedure;
            command.Parameters.AddWithValue("@id", Convert.ToInt32(lb.CommandArgument));

            if (con.State == ConnectionState.Closed)
            {
                con.Open();
            }
            command.ExecuteNonQuery();
            con.Close();

            gridbind();
            clr();

            btnadd.Text = "Add";

        }

        protected void btnCancle_Click(object sender, EventArgs e)
        {
            btnadd.Text = "Add";
            clr();
        }
        private void clr()
        {
            lblpath.Visible = false;
            txtnm.Text = "";
            rblgen.SelectedValue = "0";
            
            foreach (ListItem li in cbquly.Items)
            {
                li.Selected = false;
            }
            ddlpost.SelectedValue = "0";

        }

}
Read More