Register Register Member Login Member Login Member Login Forgot Password ??
PHP , ASP , ASP.NET, VB.NET, C#, Java , jQuery , Android , iOS , Windows Phone
 

Registered : 109,027

HOME > Entity Framework (EF) สอนเขียน LINQ to Entities บน .NET Application > ASP.Net ตอนที่ 4 : Add Data (LINQ, Entity Framework)



Clound SSD Virtual Server

ASP.Net ตอนที่ 4 : Add Data (LINQ, Entity Framework)

ASP.Net ตอนที่ 4 : Add Data (LINQ, Entity Framework) ในตัวอย่างที่ 4 จะเป็นการออกแบบ Web Form สำหรับ Input ข้อมูล และ Add Entity ด้วยการรับค่าที่ Input ไปจัดเก็บลงใน Table ผ่าน Model Entities โดยในตัวอย่างนี้จะสร้าง Web Form ขึ้นมา 2 Form คือ Form แรกใช้แสดงข้อมูลรายการทั้งหมด ส่วน Form ที่สองจะเป็น Form สำหรับการ Input ข้อมูล โดยรับข้อมูลจากการ Input นำไป Insert ลงใน Table ผ่านคำสั่งของ LINQ to Entities

Add Data

Example : การใช้งาน LINQ to Entities เพื่อรับค่าจาก Form แล้ว Insert ข้อมูลลงใน Table

Default.aspx ใช้สำหรับแสดงข้อมูลทั้งหมดบน GridView

Add Data

Add.aspx เป็น Web Form สำหรับ Input และ Insert ข้อมูลใหม่

Add Data

ไฟล์ Default.aspx และ Default.aspx.cs สำหรับแสดงรายการใน GridView

Code Default.aspx (HTML)
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="frmMain" runat="server">
        <asp:GridView ID="myGridView" runat="server" AutoGenerateColumns="False" OnRowDataBound="myGridView_RowDataBound">
            <Columns>
                <asp:TemplateField HeaderText="Customer ID">
                    <ItemTemplate>
                        <asp:Label ID="lblCustomerID" runat="server"></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Name">
                    <ItemTemplate>
                        <asp:Label ID="lblName" runat="server"></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Email">
                    <ItemTemplate>
                        <asp:Label ID="lblEmail" runat="server"></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Country Code">
                    <ItemTemplate>
                        <asp:Label ID="lblCountryCode" runat="server"></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Budget">
                    <ItemTemplate>
                        <asp:Label ID="lblBudget" runat="server"></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Used">
                    <ItemTemplate>
                        <asp:Label ID="lblUsed" runat="server"></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>

        <br />
        <asp:Button ID="btnAdd" runat="server" OnClick="btnAdd_Click" Text="Add" />

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









Code Default.aspx.cs (C#)
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            BindData();
        }

        protected void BindData()
        {
            // Create new entities Object
            using (var db = new myDatabaseEntities())
            {
                // Get data from CUSTOMER
                var ds = (from c in db.CUSTOMER
                          select new
                          {
                              c.CUSTOMER_ID,
                              c.NAME,
                              c.EMAIL,
                              c.COUNTRY_CODE,
                              c.BUDGET,
                              c.USED
                          }).ToList();

                // Assign to GridView
                if (ds.Count > 0)
                {
                    this.myGridView.DataSource = ds;
                    this.myGridView.DataBind();
                }
            }
        }

        protected void myGridView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow && DataBinder.Eval(e.Row.DataItem, "CUSTOMER_ID") != null)
            {
                //*** CustomerID ***//
                Label lblCustomerID = (Label)(e.Row.FindControl("lblCustomerID"));
                if (lblCustomerID != null)
                {
                    lblCustomerID.Text = DataBinder.Eval(e.Row.DataItem, "CUSTOMER_ID").ToString();
                }

                //*** Name ***//
                Label lblName = (Label)(e.Row.FindControl("lblName"));
                if (lblName != null)
                {
                    lblName.Text = DataBinder.Eval(e.Row.DataItem, "NAME").ToString();
                }

                //*** Email ***//
                Label lblEmail = (Label)(e.Row.FindControl("lblEmail"));
                if (lblEmail != null)
                {
                    lblEmail.Text = DataBinder.Eval(e.Row.DataItem, "EMAIL").ToString();
                }

                //*** CountryCode ***//
                Label lblCountryCode = (Label)(e.Row.FindControl("lblCountryCode"));
                if (lblCountryCode != null)
                {
                    lblCountryCode.Text = DataBinder.Eval(e.Row.DataItem, "COUNTRY_CODE").ToString();
                }

                //*** Budget ***//
                Label lblBudget = (Label)(e.Row.FindControl("lblBudget"));
                if (lblBudget != null)
                {
                    lblBudget.Text = DataBinder.Eval(e.Row.DataItem, "BUDGET").ToString();
                }

                //*** Used ***//
                Label lblUsed = (Label)(e.Row.FindControl("lblUsed"));
                if (lblUsed != null)
                {
                    lblUsed.Text = DataBinder.Eval(e.Row.DataItem, "USED").ToString();
                }

            }
  
        }
        protected void btnAdd_Click(object sender, EventArgs e)
        {
            Response.Redirect("Add.aspx");
        }

    }


ไฟล์ Add.aspx และ Add.aspx.cs สำหรับเพิ่มหรือ Insert ข้อมูล

Code Add.aspx (HTML)
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="frmMain" runat="server">
        <div>
            <table width="353" border="1">
                <tr>
                    <td width="102">
                        <asp:Label ID="Label1" runat="server" Text="Customer ID"></asp:Label></td>
                    <td width="235">
                        <asp:TextBox ID="txtCustomerID" runat="server"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td>
                        <asp:Label ID="Label2" runat="server" Text="Name"></asp:Label>
                    </td>
                    <td>
                        <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td>
                        <asp:Label ID="Label3" runat="server" Text="Email"></asp:Label></td>
                    <td>
                        <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td>
                        <asp:Label ID="Label4" runat="server" Text="Country Code"></asp:Label></td>
                    <td>
                        <asp:TextBox ID="txtCountryCode" runat="server"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td>
                        <asp:Label ID="Label5" runat="server" Text="Budget"></asp:Label></td>
                    <td>
                        <asp:TextBox ID="txtBudget" runat="server"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td>
                        <asp:Label ID="Label6" runat="server" Text="Used"></asp:Label></td>
                    <td>
                        <asp:TextBox ID="txtUsed" runat="server"></asp:TextBox>
                    </td>
                </tr>
            </table>
        </div>
        <p>
            <asp:Button ID="btnSave" runat="server" OnClick="btnSave_Click" Text="Save" />
        </p>
    </form>
</body>
</html>

Code Add.aspx.cs (C#)
    public partial class Add : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if(!Page.IsPostBack)
            {
                this.txtCustomerID.Text = string.Empty;
                this.txtName.Text = string.Empty;
                this.txtEmail.Text = string.Empty;
                this.txtCountryCode.Text = string.Empty;
                this.txtBudget.Text = string.Empty;
                this.txtUsed.Text = string.Empty;
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            using (var db = new myDatabaseEntities())
            {
                // Get Param
                string strCustomerID = this.txtCustomerID.Text;
                string strName = this.txtName.Text;
                string strEmail = this.txtEmail.Text;
                string strCountryCode = this.txtCountryCode.Text;
                decimal strBudget = Convert.ToDecimal(this.txtBudget.Text);
                decimal strUsed = Convert.ToDecimal(this.txtUsed.Text);

                // Insert data to CUSTOMER
                var ds = (from c in db.CUSTOMER
                          where c.CUSTOMER_ID == strCustomerID
                          select c).FirstOrDefault();
                // Insert
                if (ds != null)
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "PopupScript", "<script>alert('" + string.Format("Customer {0} Exists in table.", strCustomerID) + "');</script>");
                }
                else
                {
                    db.CUSTOMER.Add(new CUSTOMER()
                    {
                        CUSTOMER_ID = strCustomerID,
                        NAME = strName,
                        EMAIL = strEmail,
                        COUNTRY_CODE = strCountryCode,
                        BUDGET = strBudget,
                        USED = strUsed,
                    });
                    db.SaveChanges();
                    Response.Redirect("Default.aspx");
                }
            }
            
        }
    }

Screenshot

Add Data

แสดงรายการข้อมูลทั้งหมดใน GridViewให้คลิกที่ Add เพื่อทำการเพิ่มข้อมูล

Add Data

แสดง Form ซึ่งเป็น Web Formสำหรับการ Input ข้อมูล ในตัวอย่างนี้จะมีการตรวจสอบข้อมูลเช่น มี Key ซ้ำหรือไม่

Add Data

จะต้องทำการกรอกข้อมูลให้ถูกต้อง

Add Data

ข้อมูลที่เพิ่มลงใน Table และแสดงผลบน GridView ด้วยการ Bind ข้อมูลใหม่หลังจากที่ได้ Insert เรียบร้อยแล้ว








Code Default.aspx.vb (VB.Net)
Public Class _Default
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then
            BindData()
        End If
    End Sub

    Protected Sub BindData()
        ' Create new entities Object
        Using db = New myDatabaseEntities()

            ' Get data from CUSTOMER
            Dim ds = (From c In db.CUSTOMER
                      Select New With { _
                        c.CUSTOMER_ID, _
                        c.NAME, _
                        c.EMAIL, _
                        c.COUNTRY_CODE, _
                        c.BUDGET, _
                        c.USED _
                    }).ToList()

            ' Assign to GridView
            If ds.Count > 0 Then
                Me.myGridView.DataSource = ds
                Me.myGridView.DataBind()
            End If
        End Using

    End Sub

    Protected Sub myGridView_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles myGridView.RowDataBound
        If e.Row.RowType = DataControlRowType.DataRow And Not IsNothing(DataBinder.Eval(e.Row.DataItem, "CUSTOMER_ID")) Then
            '*** CustomerID ***'
            Dim lblCustomerID As Label = DirectCast(e.Row.FindControl("lblCustomerID"), Label)
            If Not IsNothing(lblCustomerID) Then
                lblCustomerID.Text = DataBinder.Eval(e.Row.DataItem, "CUSTOMER_ID").ToString()
            End If

            '*** Name ***'
            Dim lblName As Label = DirectCast(e.Row.FindControl("lblName"), Label)
            If Not IsNothing(lblName) Then
                lblName.Text = DataBinder.Eval(e.Row.DataItem, "NAME").ToString()
            End If

            '*** Email ***'
            Dim lblEmail As Label = DirectCast(e.Row.FindControl("lblEmail"), Label)
            If Not IsNothing(lblEmail) Then
                lblEmail.Text = DataBinder.Eval(e.Row.DataItem, "EMAIL").ToString()
            End If

            '*** CountryCode ***'
            Dim lblCountryCode As Label = DirectCast(e.Row.FindControl("lblCountryCode"), Label)
            If Not IsNothing(lblCountryCode) Then
                lblCountryCode.Text = DataBinder.Eval(e.Row.DataItem, "COUNTRY_CODE").ToString()
            End If

            '*** Budget ***'
            Dim lblBudget As Label = DirectCast(e.Row.FindControl("lblBudget"), Label)
            If Not IsNothing(lblBudget) Then
                lblBudget.Text = DataBinder.Eval(e.Row.DataItem, "BUDGET").ToString()
            End If

            '*** Used ***'
            Dim lblUsed As Label = DirectCast(e.Row.FindControl("lblUsed"), Label)
            If Not IsNothing(lblUsed) Then
                lblUsed.Text = DataBinder.Eval(e.Row.DataItem, "USED").ToString()
            End If
        End If
    End Sub

    Protected Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
        Response.Redirect("Add.aspx")
    End Sub

End Class


Code Add.aspx.vb (VB.Net)
Public Class Add
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then
            Me.txtCustomerID.Text = String.Empty
            Me.txtName.Text = String.Empty
            Me.txtEmail.Text = String.Empty
            Me.txtCountryCode.Text = String.Empty
            Me.txtBudget.Text = String.Empty
            Me.txtUsed.Text = String.Empty
        End If
    End Sub

    Protected Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
        Using db = New myDatabaseEntities()
            ' Get Param
            Dim strCustomerID As String = Me.txtCustomerID.Text
            Dim strName As String = Me.txtName.Text
            Dim strEmail As String = Me.txtEmail.Text
            Dim strCountryCode As String = Me.txtCountryCode.Text
            Dim strBudget As Decimal = Convert.ToDecimal(Me.txtBudget.Text)
            Dim strUsed As Decimal = Convert.ToDecimal(Me.txtUsed.Text)

            ' Insert data to CUSTOMER
            Dim ds = (From c In db.CUSTOMER
                      Where c.CUSTOMER_ID = strCustomerID
                    Select c).FirstOrDefault()
            ' Insert
            If ds IsNot Nothing Then
                ClientScript.RegisterStartupScript(Me.GetType, "PopupScript", "<script>alert('" + String.Format("Customer {0} Exists in table.", strCustomerID) + "');</script>")
            Else
                db.CUSTOMER.Add(New CUSTOMER() With { _
                    .CUSTOMER_ID = strCustomerID, _
                    .NAME = strName, _
                    .EMAIL = strEmail, _
                    .COUNTRY_CODE = strCountryCode, _
                    .BUDGET = strBudget, _
                    .USED = strUsed _
                })
                db.SaveChanges()
                Response.Redirect("Default.aspx")
            End If
        End Using
    End Sub

End Class


   
Share


ช่วยกันสนับสนุนรักษาเว็บไซต์ความรู้แห่งนี้ไว้ด้วยการสนับสนุน Source Code 2.0 ของทีมงานไทยครีเอท


ลองใช้ค้นหาข้อมูล


   


Bookmark.   
       
  By : ThaiCreate.Com Team (บทความเป็นลิขสิทธิ์ของเว็บไทยครีเอทห้ามนำเผยแพร่ ณ เว็บไซต์อื่น ๆ)
  Score Rating :  
  Create/Update Date : 2015-10-02 21:21:40 / 2017-03-15 14:37:10
  Download : No files
 Sponsored Links / Related

 
รู้จัก Entity Framework (EF) คืออะไร ใช้ทำอะไร และมีประโยชน์อย่างไรบน .Net Framework
Rating :

 
สร้าง Entity Framework เพื่อติดต่อกับ Database การสร้าง Model Entities บน Visual Studio
Rating :

 
List(T) คืออะไร Generic Class ของ List ใช้งานกับ Entity Framework และ LINQ to Entities
Rating :

 
เรียกใช้งาน Entity Framework การ Select ข้อมูลจาก Entities แสดงผลบน DataSource Control
Rating :

 
Loop and Get Data (LINQ, Entity Framework)
Rating :

 
WHERE Clause (LINQ, Entity Framework)
Rating :

 
Entity & Relation (Foreign Key , CasCade , Delete , Update) (LINQ, Entity Framework)
Rating :

 
WHERE IN / NOT IN (LINQ, Entity Framework)
Rating :

 
WHERE LIKE / NOT LIKE (LINQ, Entity Framework)
Rating :

 
ORDER BY and Sorting Data (ASC, DESC) (LINQ, Entity Framework)
Rating :

 
WHERE BETWEEN (LINQ, Entity Framework)
Rating :

 
Compare DateTime (LINQ, Entity Framework)
Rating :

 
Join Clause (LINQ, Entity Framework)
Rating :

 
Left Join (LINQ, Entity Framework)
Rating :

 
Right Join (LINQ, Entity Framework)
Rating :

 
Union (LINQ, Entity Framework)
Rating :

 
VIEW Table (LINQ, Entity Framework)
Rating :

 
Add Entity : Insert Rows Into Database (LINQ, Entity Framework)
Rating :

 
Update Entity : Update Rows in Database (LINQ, Entity Framework)
Rating :

 
Delete Entity : Delete Rows in Database (LINQ, Entity Framework)
Rating :

 
Entity Framework and Try Catch Exception (LINQ, Entity Framework)
Rating :

 
Entity Framework and Transaction Scope (LINQ, Entity Framework)
Rating :

 
Get Connection String & Connection State (LINQ, Entity Framework)
Rating :

 
Select Entity to List<Object> (LINQ, Entity Framework)
Rating :

 
Entity Execute SQL Query : INSERT/UPDATE/DELETE (LINQ, Entity Framework)
Rating :

 
Entity Select SQL (Statement) Query (LINQ, Entity Framework)
Rating :

 
Entity and Stored Procedure (LINQ, Entity Framework)
Rating :

 
เทคนิคการใช้ IntelliTrace ในการ Debug ตรวจสอบ Performance ของโปรแกรม
Rating :

 
Windows Form ตอนที่ 1 : DataGridView List Show Data (LINQ, Entity Framework)
Rating :

 
Windows Form ตอนที่ 2 : DataGridView Search Data (LINQ, Entity Framework)
Rating :

 
Windows Form ตอนที่ 3 : DataGridView Display Master-Detail (LINQ, Entity Framework)
Rating :

 
Windows Form ตอนที่ 4 : Add Data (LINQ, Entity Framework)
Rating :

 
Windows Form ตอนที่ 5 : Update Data (LINQ, Entity Framework)
Rating :

 
Windows Form ตอนที่ 6 : Delete Data (LINQ, Entity Framework)
Rating :

 
ASP.Net ตอนที่ 1 : GridView List Show Data (LINQ, Entity Framework)
Rating :

 
ASP.Net ตอนที่ 2 : GridView Search Data (LINQ, Entity Framework)
Rating :

 
ASP.Net ตอนที่ 3 : Display Master-Detail (LINQ, Entity Framework)
Rating :

 
ASP.Net ตอนที่ 5 : Update Data (LINQ, Entity Framework)
Rating :

 
ASP.Net ตอนที่ 6 : Delete Data (LINQ, Entity Framework)
Rating :

 
การใช้งาน Entity Framework กับ MySQL Database (LINQ to Entities - MySQL Database)
Rating :

 
การใช้งาน Entity Framework กับ Oracle Database (LINQ to Entities - Oracle Database)
Rating :


ThaiCreate.Com Forum


Comunity Forum Free Web Script
Jobs Freelance Free Uploads
Free Web Hosting Free Tools

สอน PHP ผ่าน Youtube ฟรี
สอน Android การเขียนโปรแกรม Android
สอน Windows Phone การเขียนโปรแกรม Windows Phone 7 และ 8
สอน iOS การเขียนโปรแกรม iPhone, iPad
สอน Java การเขียนโปรแกรม ภาษา Java
สอน Java GUI การเขียนโปรแกรม ภาษา Java GUI
สอน JSP การเขียนโปรแกรม ภาษา Java
สอน jQuery การเขียนโปรแกรม ภาษา jQuery
สอน .Net การเขียนโปรแกรม ภาษา .Net
Free Tutorial
สอน Google Maps Api
สอน Windows Service
สอน Entity Framework
สอน Android
สอน Java เขียน Java
Java GUI Swing
สอน JSP (Web App)
iOS (iPhone,iPad)
Windows Phone
Windows Azure
Windows Store
Laravel Framework
Yii PHP Framework
สอน jQuery
สอน jQuery กับ Ajax
สอน PHP OOP (Vdo)
Ajax Tutorials
SQL Tutorials
สอน SQL (Part 2)
JavaScript Tutorial
Javascript Tips
VBScript Tutorial
VBScript Validation
Microsoft Access
MySQL Tutorials
-- Stored Procedure
MariaDB Database
SQL Server Tutorial
SQL Server 2005
SQL Server 2008
SQL Server 2012
-- Stored Procedure
Oracle Database
-- Stored Procedure
SVN (Subversion)
แนวทางการทำ SEO
ปรับแต่งเว็บให้โหลดเร็ว


Hit Link
   







Load balance : Server 01
ThaiCreate.Com Logo
© www.ThaiCreate.Com. 2003-2024 All Rights Reserved.
ไทยครีเอทบริการ จัดทำดูแลแก้ไข Web Application ทุกรูปแบบ (PHP, .Net Application, VB.Net, C#)
[Conditions Privacy Statement] ติดต่อโฆษณา 081-987-6107 อัตราราคา คลิกที่นี่