Thursday, 13 October 2016

MVC Complete Project With Code

Creating Cascading DropDownList In MVC 5 Using Entity Framework 6.0 Database First Step By Step 


step 1:

Create database first 
 Create database cascadingcountrystatecity;
USE [cascadingcountrystatecity]
GO
/****** Object:  Table [dbo].[C_State]    Script Date: 10/13/16 3:27:34 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[C_State](
[StId] [int] IDENTITY(1,1) NOT NULL,
[ConId] [int] NULL,
[StName] [nvarchar](100) NULL,
[DateTimeStamp] [datetime] NOT NULL,
PRIMARY KEY CLUSTERED 
(
[StId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
UNIQUE NONCLUSTERED 
(
[StName] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[City]    Script Date: 10/13/16 3:27:34 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[City](
[CityId] [int] IDENTITY(1,1) NOT NULL,
[Stid] [int] NULL,
[CityName] [nvarchar](100) NULL,
[DateTimeStamp] [datetime] NOT NULL,
PRIMARY KEY CLUSTERED 
(
[CityId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
UNIQUE NONCLUSTERED 
(
[CityName] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[country]    Script Date: 10/13/16 3:27:34 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[country](
[ConId] [int] IDENTITY(1,1) NOT NULL,
[ConName] [nvarchar](100) NULL,
[DateTimeStamp] [datetime] NOT NULL,
PRIMARY KEY CLUSTERED 
(
[ConId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
UNIQUE NONCLUSTERED 
(
[ConName] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[employee]    Script Date: 10/13/16 3:27:34 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[employee](
[Empid] [int] IDENTITY(1,1) NOT NULL,
[EmpName] [nvarchar](100) NULL,
[ConId] [int] NULL,
[StId] [int] NULL,
[CityId] [int] NULL,
PRIMARY KEY CLUSTERED 
(
[Empid] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
ALTER TABLE [dbo].[C_State] ADD  DEFAULT (getdate()) FOR [DateTimeStamp]
GO
ALTER TABLE [dbo].[City] ADD  DEFAULT (getdate()) FOR [DateTimeStamp]
GO
ALTER TABLE [dbo].[country] ADD  DEFAULT (getdate()) FOR [DateTimeStamp]
GO
ALTER TABLE [dbo].[C_State]  WITH CHECK ADD FOREIGN KEY([ConId])
REFERENCES [dbo].[country] ([ConId])
GO
ALTER TABLE [dbo].[City]  WITH CHECK ADD FOREIGN KEY([Stid])
REFERENCES [dbo].[C_State] ([StId])
GO
ALTER TABLE [dbo].[employee]  WITH CHECK ADD FOREIGN KEY([CityId])
REFERENCES [dbo].[City] ([CityId])
GO
ALTER TABLE [dbo].[employee]  WITH CHECK ADD FOREIGN KEY([ConId])
REFERENCES [dbo].[country] ([ConId])
GO
ALTER TABLE [dbo].[employee]  WITH CHECK ADD FOREIGN KEY([StId])
REFERENCES [dbo].[C_State] ([StId])
GO
USE [master]
GO
ALTER DATABASE [cascadingcountrystatecity] SET  READ_WRITE 
GO



1: Select and copy Above Script 
2: Open sql server management studio 
3: open query window 
4: paste and execute above query :


Step 2:

1: Open visual studio 2013 and above 
2: Create web application with mvc 
3: Right click on models folder 

coming soon    

  










Friday, 15 April 2016

Validation and Data Annotations In MVC 5


Validation and  Data Annotations  In MVC 5

Validation is way to check data or information is authentic or not. Here we are discuses How to validate data or information from client Side Step By step
step 1:
use namespace 
System.ComponentModel.DataAnnotations;
step2:
Create Model class
Let Us consider Create Model Class employee
and some property define as 

public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string EmailConfirm { get; set; }
public int Age { get; set; }
public decimal Price { get; set; }


step3

We are Disused Required

 [Required]
public string FirstName { get; set; }

[Required]

public string LastName { get; set; }

[Required]

[StringLength(160)]
public string FirstName { get; set; }


[Required]

[StringLength(160)]
public string LastName { get; set; }

[Required]
[StringLength(160, MinimumLength=3)]
public string FirstName { get; set; }


Step 4:

RegularExpression

Some properties of Order require more than a simple presence or length check. For example, 
you want to ensure the Email property of an  Order contains a valid, working e-mail address. 
Unfortunately, ensuring an e-mail address is working without sending a mail message and waiting 
for a response is practically impossible. What you can do instead is ensure the value  looks  like  a 
working e-mail address using a regular expression:


[RegularExpression(@"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}")]
public string Email { get; set; }


Range
The  Range attribute specify  minimum and maximum constraints for a numerical value. If the 
 field  only wanted to serve middle-aged customers, you could add an Age  property to the 
Order class and use the  Range attribute as in the following code:


[Range(35,44)]
public int Age { get; set; }

The values are inclusive. The Range attribute can work with integers and doubles, and 
another overloaded version of the constructor takes a  Type parameter and two strings (which can 
allow you to add a range to date and decimal properties, for example).

[Range(typeof(decimal), "0.00", "49.99")]
public decimal Price { get; set; }


Compare:

Compare ensures two properties on a model object have the same value. For example, you might 
want to force customers to enter their e-mail address twice to ensure they didn’t make a typographi-
cal error:

[RegularExpression(@"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}")]
public string Email { get; set; }

[Compare("Email")]
public string EmailConfirm { get; set; }

[Required]
[DataType(DataType.Password)]
[Display(Name="Password")]
public string Password { get; set; }


Remote

The ASP.NET MVC framework adds an additional Remote validation attribute. This attribute is in the  System.Web.Mvc namespace.
The  Remote attribute enables you to perform client-side validation with a server callback. Take, for example, the  UserName  property of the RegisterModel  class in the MVC Music Store. No two user should have the same  UserName  value, but validating the value on the client to ensure the value is unique is difi cult (to do so you would have to send every single username from the database to the client). With the Remote attribute you can send the  UserName  value to the server, and compare the value against the values in the

database.[Remote("CheckUserName","Account")]
public string UserName { get; set; }


Monday, 11 April 2016

ASP.NET MVC Attribute Routing

ASP.NET MVC Attribute Routing:

Attribute Routing is a new option for specifying routes by placing annotations on your controller classes or action methods.

ASP.NET Identity

ASP.NET Identity:

The membership and authentication systems in MVC 5 have been completely rewritten as part of the new ASP.NET Identity system. This new system moves beyond some outdated constraints of the previous ASP.NET Membership system, while adding some sophistication and configuration to the Simple Membership system that shipped with MVC 4.

Here are some of the top new features in ASP.NET Identity: 

➤ One ASP.NET Identity system: In support of the One ASP.NET focus we discussed earlier, the new ASP.NET Identity was designed to work across the ASP.NET family (MVC, Web Forms, Web Pages, Web API, Signal R, and hybrid applications using any combination).
➤ Control over user profile data:

Although it’s a frequently used application for storing additional, custom information about your users, the ASP.NET Membership system made doing it very difficult. ASP.NET Identity makes storing additional user information (for example, account numbers, social media information, and contact address) as easily as adding properties to the model class that represents the user.
➤ Control over persistence:

By default, all user information is stored using Entity Framework Code First. This gives you both the simplicity and control you’re used to with Entity Framework Code First. However, you can plug in any other persistence mechanism you want, including other ORMs, databases, your own custom web services, and so on.
➤ Testability:

The ASP.NET Identity API was designed using interfaces. These allow you to write unit tests for your user-related application code.
➤ Claims Based:

Although ASP.NET Identity continues to offer support for user roles, it also supports claims-based authentication. Claims are a lot more expressive than roles, so this gives you a lot more power and flexibility. Whereas role membership is a simple Boolean value (a user either is or isn’t in the Administrator role), a user claim can carry rich information, such as a user’s membership level or identity specifics.
➤ Login providers:

 Rather than just focusing on username / password authentication, ASP.NET Identity understands that users often are authenticated through social providers (for example, Microsoft Account, Facebook, or Twitter) and Windows Azure Active Directory.

➤ NuGet distribution:

ASP.NET Identity is installed in your applications as a NuGet package. This means you can install it separately, as well as upgrade to newer releases with the simplicity of updating a single NuGet package.

History of ASP.Net MVC

History of ASP.Net MVC:

ASP.NET MVC 1

ASP.NET MVC 1 was released in february 2007 byScott Guthrie of Microsoft sketched out the core of ASP.NET MVC while flying on a plane to a conference on the East Coast of the United States.

 It was a simple application, containing a few hundred lines of code, but the promise and potential it offered for parts of the Microsoft web developer audience was huge. As the legend goes, at the Austin ALT.NET conference in October 2007 in Redmond, Washington, ScottGu showed a group of developers “this cool thing I wrote on a plane” and asked whether they saw the need and what they thought of it. It was a hit. In fact, many people were involved with the original prototype, codenamed Scalene. Eilon Lipton e-mailed the fi rst prototype to the team in September 2007, and he and ScottGu bounced prototypes, code, and ideas back and forth.

ASP.NET MVC 2

ASP.NET MVC 2 was released  in March 2010.

Some of the main features in MVC 2 included:

 ➤ UI helpers with automatic scaffolding with customizable templates
 ➤ Attribute-based model validation on both the client and server
➤ Strongly typed HTML helpers
➤ Improved Visual Studio tooling
➤ Support for partitioning large applications into areas
➤ Asynchronous controllers support
➤ Support for rendering subsections of a page/site using Html.RenderAction
➤ Lots of new helper functions, utilities, and API enhancements

ASP.NET MVC 3 

ASP.NET MVC 3 released  just 10 months after MVC 2, driven by the release date for Web Matrix. 

Some of the top features in MVC 3 included: 

➤ The Razor view engine
➤ Support for .NET 4 Data Annotations
➤ Improved model validation
➤ Greater control and flexibility with support for dependency resolution and global action filters
➤ Better JavaScript support with unobtrusive JavaScript, jQuery Validation, and JSON binding
➤ Use of NuGet to deliver software and manage dependencies throughout the platform

ASP.NET MVC 4


The MVC 4 release built on a pretty mature base and is able to focus on some more advanced scenarios.
Some top features include:
➤ ASP.NET Web API
➤ Enhancements to default project templates
➤ Mobile project template using jQuery Mobile
➤ Display modes
➤ Task support for asynchronous controllers
➤ Bundling and minifi cation Because MVC 4 is still a pretty recent release, we explain a few of these features in a little more detail here and describe them in more detail throughout the book.



ASP.NET MVC 5 

MVC 5 was released along with Visual Studio 2013 in October 2013. The main focus of this release was on a “One ASP.NET” initiative (described in the following sections) and core enhancements across the ASP.NET frameworks.

Some of the top features include: 

➤ One ASP.NET
➤ New Web Project Experience
 ➤ ASP.NET Identity
➤ Bootstrap templates
 ➤ Attribute Routing
➤ ASP.NET scaffolding
➤ Authentication fi lters
➤ Filter overrides

Introduction of ASP.NET MVC

Introduction of ASP.Net MVC Model View Control:

ASP.NET MVC is a framework for building web applications that applies the general Model View Controller pattern to the ASP.NET framework.

Model-View-Controller (MVC) has been an important architectural pattern in computer science for many years. Originally named Thing-Model-View-Editor in 1979,

The MVC separates the user interface (UI) of an application into three main aspects:

 ➤ The Model: A set of classes that describes the data you’re working with as well as the business rules for how the data can be changed and manipulated

The View: Defines how the application’s UI will be displayed

The Controller: A set of classes that handles communication from the user, overall application fl ow, and application-specifi c logic


The MVC pattern is used frequently in web programming. With ASP.NET MVC.

 ➤ Models: These are the classes that represent the domain you are interested in. These domain objects often encapsulate data stored in a database as well as code that manipulates the data and enforces domain-specifi c business logic. With ASP.NET MVC, this is most likely a Data Access Layer of some kind, using a tool like Entity Framework or NHibernate combined with custom code containing domain-specifi c logic.

➤ View: This is a template to dynamically generate HTML.


➤ Controller: This is a special class that manages the relationship between the View and the Model. It responds to user input, talks to the Model, and decides which view to render (if any). In ASP.NET MVC, this class is conventionally denoted by the suffix Controller.

Wednesday, 3 February 2016

asp .net How we insert update delete using grid view


First you copy paste design view on the page



 <h1 class="page-header">Add Category</h1>
 
    <label>Category Name</label>
    <asp:TextBox ID="txtcatname" runat="server" class="form-control"></asp:TextBox>

    <label>Category Image</label>
    <asp:FileUpload ID="FUPropImage" runat="server" CssClass="form-control" />
                                                    <asp:RegularExpressionValidator ID="rgvPropImage" runat="server" ControlToValidate="FUPropImage"
                                                        CssClass="red" Display="dynamic" ErrorMessage="<img src='../icon/error.png' width='12px' height='12px'/>"
                                                        ToolTip="Invalid Format!" ValidationExpression="^.+(.gif|.GIF|.jpg|.JPG|.png|.PNG|.tif|.TIF)$"
                                                        ValidationGroup="ENTRY"></asp:RegularExpressionValidator>
                                                    <strong class="textbox_content">&nbsp; Formats </strong><span style="color: orange">
                                                        .gif|.GIF|.jpg|.JPG|.png|.PNG|.tif|.TIF</span>
 
    <label>Category Detail</label>
    <asp:TextBox ID="txtcatdtl" textmode="MultiLine" runat="server" Height="150px" Width="100%" ></asp:TextBox>

    <label></label>

    <asp:Button ID="btnaddcat" runat="server" Text="ADD CATEGORY" class="btn btn-lg btn-primary btn-block" OnClick="btncat_Click" />
    <div class="panel">
         <h2 class="sub-header">Categories List</h2>
         <div class="table-responsive">
           
             <asp:GridView ID="GridView1" runat="server" ShowHeaderWhenEmpty="True"
            AutoGenerateColumns="False" onrowdeleting="RowDeleting"
            OnRowCancelingEdit="cancelRecord" OnRowEditing="editRecord"
            OnRowUpdating="updateRecord" CellPadding="4" GridLines="None" Width="100%"
            ForeColor="#333333" AllowPaging="True" AllowSorting="True" OnPageIndexChanging="GridView1_PageIndexChanging" >
            <RowStyle BackColor="#E3EAEB" />
            <AlternatingRowStyle BackColor="White" />

            <Columns>

            <asp:TemplateField>
                <EditItemTemplate>
                    Cat
                </EditItemTemplate>
            <HeaderTemplate>Category Id</HeaderTemplate>
            <ItemTemplate>
            <asp:Label ID ="lblId" runat="server" Text='<%# Bind("CatID") %>'></asp:Label>
            </ItemTemplate>
            </asp:TemplateField>

            <asp:TemplateField>
            <HeaderTemplate>Category Name</HeaderTemplate>
            <ItemTemplate>
            <asp:Label ID ="lblcatName" runat="server" Text='<%# Bind("CatName") %>'></asp:Label>
            </ItemTemplate>
            <EditItemTemplate>
            <asp:TextBox ID="txtName" runat="server" Text='<%# Bind("CatName") %>' MaxLength="50"></asp:TextBox>
            <asp:RequiredFieldValidator ID="rfvtxtName" runat="server" Text="*" ToolTip="Enter name" ControlToValidate="txtName"></asp:RequiredFieldValidator>
            <asp:RegularExpressionValidator ID="revtxtName" runat="server" Text="*" ToolTip="Enter alphabate " ControlToValidate="txtName" ValidationExpression="^[a-zA-Z'.\s]{1,40}$"></asp:RegularExpressionValidator>
         
            </EditItemTemplate>
            <FooterTemplate>
            <asp:TextBox ID="txtNewName" runat="server" MaxLength="50"></asp:TextBox>
            <asp:RequiredFieldValidator ID="rfvtxtNewName" runat="server" Text="*" ToolTip="Enter name" ControlToValidate="txtNewName"></asp:RequiredFieldValidator>
            <asp:RegularExpressionValidator ID="revtxtNewName" runat="server" Text="*" ToolTip="Enter alphabate " ControlToValidate="txtNewName" ValidationExpression="^[a-zA-Z'.\s]{1,40}$"></asp:RegularExpressionValidator>
       
            </FooterTemplate>
            </asp:TemplateField>
         
            <asp:TemplateField>
            <HeaderTemplate>Category Description</HeaderTemplate>
            <ItemTemplate>
            <asp:Label ID="lblcatdis" runat ="server" Text='<%# Bind("CatRemark") %>'></asp:Label>
            </ItemTemplate>
                <EditItemTemplate>
                    <asp:TextBox ID="txtcatre" runat="server" Text='<%# Bind("CatRemark") %>'></asp:TextBox>
                </EditItemTemplate>
            <FooterTemplate>
            <asp:TextBox ID="txtNewAge" runat="server"></asp:TextBox></FooterTemplate>
            </asp:TemplateField>

            <asp:TemplateField>
            <HeaderTemplate>Photo</HeaderTemplate>
            <ItemTemplate>
            <asp:Image ID="imgPhoto" Width="100px" Height="100px" runat="server" text="Photo" ImageUrl='<%# Bind("CatImage") %>' />
            </ItemTemplate>
            <EditItemTemplate>
            <asp:FileUpload ID="fuPhoto" runat="server" ToolTip="select Employee Photo"/>
            <asp:RegularExpressionValidator ID="revfuPhoto" runat="server" Text="*" ToolTip="Image formate only" ControlToValidate="fuPhoto" ValidationExpression="[a-zA-Z0_9].*\b(.jpeg|.JPEG|.jpg|.JPG|.jpe|.JPE|.png|.PNG|.mpp|.MPP|.gif|.GIF)\b"></asp:RegularExpressionValidator>
            </EditItemTemplate>
            <FooterTemplate>
            <asp:FileUpload ID="fuNewPhoto" runat="server" ToolTip="select Employee Photo"/>
            <asp:RequiredFieldValidator ID="rfvfuNewPhoto" runat="server" ErrorMessage="*" ToolTip="Select Photo" ControlToValidate="fuNewPhoto"></asp:RequiredFieldValidator>
            <asp:RegularExpressionValidator ID="revfuNewPhoto" runat="server" Text="*" ToolTip="Image formate only" ControlToValidate="fuNewPhoto" ValidationExpression="[a-zA-Z0_9].*\b(.jpeg|.JPEG|.jpg|.JPG|.jpe|.JPE|.png|.PNG|.mpp|.MPP|.gif|.GIF)\b"></asp:RegularExpressionValidator>
            </FooterTemplate>
            </asp:TemplateField>

            <asp:TemplateField>
            <HeaderTemplate>Operation</HeaderTemplate>
            <ItemTemplate>
            <asp:Button ID="btnEdit" runat="server" CommandName="Edit" Text="Edit" OnClick="btnEdit_Click" />
            <asp:Button ID="btnDelete" runat="server" CommandName="Delete" Text="Delete" CausesValidation="true" OnClientClick="return confirm('Are you sure?')" OnClick="btnDelete_Click" />
            </ItemTemplate>
            <EditItemTemplate>
            <asp:Button ID="btnUpdate" runat="server" CommandName="Update" Text="Update" OnClick="btnUpdate_Click" />
            <asp:Button ID="btnCancel" runat="server" CommandName="Cancel" Text="Cancel" CausesValidation="false" OnClick="btnCancel_Click" />
            </EditItemTemplate>

            <FooterTemplate>
            <asp:Button ID="btnNewInsert" runat="server" Text="Insert" OnClick="InsertNewRecord"/>
            <asp:Button ID="btnNewCancel" runat="server" Text="Cancel" OnClick="AddNewCancel" CausesValidation="false" />
            </FooterTemplate>      
            </asp:TemplateField>        
            </Columns>
            <EditRowStyle BackColor="#7C6F57" />
            <EmptyDataTemplate>
                      No record available                  
            </EmptyDataTemplate>    
            <FooterStyle BackColor="#1C5E55" ForeColor="White" Font-Bold="True" />
            <HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
                 <PagerSettings FirstPageText="First" LastPageText="Last" NextPageText="Next" />
            <PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
            <RowStyle HorizontalAlign="Center" />
            <SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />

        </asp:GridView>
         
     
    </div>
        </div>
    c# code


protected void cancelRecord(object sender, GridViewCancelEditEventArgs e)
    {
        GridView1.EditIndex = -1;
        FillGridView();



    }
    protected void RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        try
        {
            GlobalClass.dt.Rows[GridView1.Rows[e.RowIndex].RowIndex].Delete();
            GlobalClass.adap.Update(GlobalClass.dt);
            // Get the image path for removing deleted's record image from server folder
            Image imgPhoto = GridView1.Rows[e.RowIndex].FindControl("imgPhoto") as Image;
            File.Delete(Server.MapPath(imgPhoto.ImageUrl));
            FillGridView();
        }
        catch
        {
            Response.Write("<script> alert('Sorry Category Not Deleted, Because It Has Sub-Category...') </script>");
        }

    }
    protected void editRecord(object sender, GridViewEditEventArgs e)
    {
     

        // Get the image path for remove old image after update record
        Image imgEditPhoto = GridView1.Rows[e.NewEditIndex].FindControl("imgPhoto") as Image;
        GlobalClass.imgEditPath = imgEditPhoto.ImageUrl;
        // Get the current row index for edit record
        GridView1.EditIndex = e.NewEditIndex;
        FillGridView();

    }
    protected void updateRecord(object sender, GridViewUpdateEventArgs e)
    {
        try
        {
            TextBox txtName = GridView1.Rows[e.RowIndex].FindControl("txtName") as TextBox;
            TextBox txtAge = GridView1.Rows[e.RowIndex].FindControl("txtcatre") as TextBox;
            FileUpload fuPhoto = GridView1.Rows[e.RowIndex].FindControl("fuPhoto") as FileUpload;
            Guid FileName = Guid.NewGuid();
            if (fuPhoto.FileName != "")
            {
                fuPhoto.SaveAs(Server.MapPath("~/proimage/img/" + FileName + ".png"));
                GlobalClass.dt.Rows[GridView1.Rows[e.RowIndex].RowIndex]["CatImage"] = "~/proimage/img/" + FileName + ".png";
                File.Delete(Server.MapPath(GlobalClass.imgEditPath));
            }
            GlobalClass.dt.Rows[GridView1.Rows[e.RowIndex].RowIndex]["CatName"] = txtName.Text.Trim();
            GlobalClass.dt.Rows[GridView1.Rows[e.RowIndex].RowIndex]["CatRemark"] =txtAge.Text.Trim();
            GlobalClass.adap.Update(GlobalClass.dt);
            GridView1.EditIndex = -1;
            Response.Write("<script> alert('Record updated Successfully...') </script>");
            FillGridView();
        }
        catch
        {
            Response.Write("<script> alert('Record updation fail...') </script>");
        }
     

    }
    protected void btncat_Click(object sender, EventArgs e)
    {
      try{
        Guid FileName = Guid.NewGuid();
        FUPropImage.SaveAs(Server.MapPath("~/proimage/img/" + FileName + ".png"));
        DataRow dr = GlobalClass.dt.NewRow();
        dr["CatName"] = txtcatname.Text.Trim();
        dr["CatRemark"] = txtcatdtl.Text;
        dr["RegDate"] = DateTime.Now.ToString("mm/dd/yyyy HH:mm:ss");
        dr["Active"] ="True";

        dr["CatImage"] = "~/proimage/img/" + FileName + ".png";
        GlobalClass.dt.Rows.Add(dr);
        GlobalClass.adap.Update(GlobalClass.dt);
     
        FillGridView();
        Response.Write("<script> alert('Category Added Successfully!!!') </script>");
     
    }
        catch
        {
            Response.Write("<script> alert('Sorry Category Not Added or Already Exist...') </script>");
        }



        }

    public string GetUniqueFileName(string filename)
    {
        try
        {
            string[] ext = new string[5];
            ext = filename.Split('.');
            return ext[0] + Guid.NewGuid().ToString() + "." + ext[ext.Length - 1];
        }
        catch (Exception ex)
        {
            return ex.ToString();
        }
    }

    public void FillGridView()
    {
        try
        {

            string cnString = ConfigurationManager.ConnectionStrings["cons"].ConnectionString;
            SqlConnection con = new SqlConnection(cnString);
            GlobalClass.adap = new SqlDataAdapter("select * from Categories", con);
            SqlCommandBuilder bui = new SqlCommandBuilder(GlobalClass.adap);
            GlobalClass.dt = new DataTable();
            GlobalClass.adap.Fill(GlobalClass.dt);
            GridView1.DataSource = GlobalClass.dt;
            GridView1.DataBind();
        }
        catch
        {
            Response.Write("<script> alert('Connection String Error...') </script>");
        }
    }


call fillgrid method in pageload event