Tuesday 2 April 2013

Insert in DetailsView in asp.net using linq


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
Design code:
<!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 align="center">
    <asp:DetailsView ID="dv" runat="server" AutoGenerateRows="false" DefaultMode="Insert"
             oniteminserting="dv_ItemInserting">
   <Fields>
  <asp:BoundField DataField="ID" HeaderText="ID" />
  <asp:BoundField DataField="NAME" HeaderText="NAME" />
  <asp:CommandField ShowInsertButton="true" CancelText="" InsertText="Save" FooterStyle-Font-Underline="false" ButtonType="Link" ControlStyle-Font-Underline="false" />
   </Fields>
    </asp:DetailsView>
    </div>
    </form>
</body>
</html>
C# code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    DataClassesDataContext o = new DataClassesDataContext();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            fill();
        }
    }
    void fill()
    {
        dv.DataSource = o.EMPs.ToList();
        dv.DataBind();
    }
    protected void dv_ItemInserting(object sender, DetailsViewInsertEventArgs e)
    {
        EMP p = new EMP();
        p.ID = Convert.ToInt32(((TextBox)dv.Rows[0].Cells[1].Controls[0]).Text);
        p.NAME = ((TextBox)dv.Rows[1].Cells[1].Controls[0]).Text;
        o.EMPs.InsertOnSubmit(p);
        o.SubmitChanges();
        Response.Write("<script>alert('one record saved.')</script>");
    }
  
  
}
page looks like.


No comments:

Post a Comment