Merhaba arkadaşlar, bu makale de GridView nesnesinin
FooterTemplate kısmına eklediğimiz Textbox ve Button ile Gridview a veri girişi
yaparak yeni satır eklemiş olacağız. Mevcut satırlardaki bilgilerin
güncellemesini, silinmesini sağlayacağız. Bu örnekte procedure metodunu
kullanılacaktır. 
GridView nesnesinin ShowFooter="True" , AutoGenerateColumns="False" yapın.
Veritabanı tablonuzu aşağıdaki gibi oluşturun.
CREATE TABLE [dbo].[productinfo1] (
    [productid]   INT          IDENTITY (1, 1) NOT NULL,
    [productname] VARCHAR (50) NULL,
    [price]       VARCHAR (50) NULL,
    [status]      VARCHAR (50) NULL,
    PRIMARY KEY CLUSTERED ([productid] ASC)
);
Procedure nuzu aşağıdaki
gibi oluşturun.
CREATE PROCEDURE [dbo].[crudoperations]
@productid
int = 0, 
@productname
varchar(50)=null, 
@price
int=0, 
@status
varchar(50) 
AS 
BEGIN 
SET NOCOUNT ON; 
---
Insert New Records 
IF @status='INSERT' 
BEGIN 
INSERT INTO productinfo1(productname,price) VALUES(@productname,@price) 
END 
---
Select Records in Table 
IF @status='SELECT' 
BEGIN 
SELECT productid,productname,price FROM productinfo1 
END 
---
Update Records in Table  
IF @status='UPDATE' 
BEGIN 
UPDATE productinfo1 SET productname=@productname,price=@price WHERE productid=@productid 
END 
---
Delete Records from Table 
IF @status='DELETE' 
BEGIN 
DELETE FROM productinfo1 where productid=@productid 
END 
SET NOCOUNT OFF 
END
Screenshot
Şekil 1
Şekil 2
Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Drawing;
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGridview();
        }
    }
    protected void BindGridview()
    {
        DataSet ds = new DataSet();
        using (SqlConnection con = new SqlConnection("Data
Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\product.mdf;Integrated
Security=True;Connect Timeout=30"))
        {
            con.Open();
            SqlCommand cmd = new SqlCommand("crudoperations", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@status", "SELECT");
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(ds);
            con.Close();
            if (ds.Tables[0].Rows.Count > 0)
            {
                gvDetails.DataSource = ds;
                gvDetails.DataBind();
            }
            else
            {
               
ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
                gvDetails.DataSource = ds;
                gvDetails.DataBind();
                int columncount = gvDetails.Rows[0].Cells.Count;
               
gvDetails.Rows[0].Cells.Clear();
                gvDetails.Rows[0].Cells.Add(new TableCell());
               
gvDetails.Rows[0].Cells[0].ColumnSpan = columncount;
                gvDetails.Rows[0].Cells[0].Text = "No Records Found. Kayıt bulunamadı!";
            }
        }
    }
    protected void gvDetails_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("AddNew"))
        {
            TextBox txtname = (TextBox)gvDetails.FooterRow.FindControl("txtpname");
            TextBox txtprice = (TextBox)gvDetails.FooterRow.FindControl("txtprice");
            crudoperations("INSERT",
txtname.Text, txtprice.Text, 0);
        }
    }
    protected void gvDetails_RowEditing(object sender, GridViewEditEventArgs e)
    {
        gvDetails.EditIndex = e.NewEditIndex;
        BindGridview();
    }
    protected void gvDetails_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        gvDetails.EditIndex = -1;
        BindGridview();
    }
    protected void gvDetails_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvDetails.PageIndex = e.NewPageIndex;
        BindGridview();
    }
    protected void gvDetails_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        int productid = Convert.ToInt32(gvDetails.DataKeys[e.RowIndex].Values["productid"].ToString());
        TextBox txtname = (TextBox)gvDetails.Rows[e.RowIndex].FindControl("txtProductname");
        TextBox txtprice = (TextBox)gvDetails.Rows[e.RowIndex].FindControl("txtProductprice");
        crudoperations("UPDATE",
txtname.Text, txtprice.Text, productid);
    }
    protected void gvDetails_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        int productid = Convert.ToInt32(gvDetails.DataKeys[e.RowIndex].Values["productid"].ToString());
        string productname = gvDetails.DataKeys[e.RowIndex].Values["productname"].ToString();
        crudoperations("DELETE",
productname, "", productid);
    }
    protected void crudoperations(string status, string productname, string price, int productid)
    {
        using (SqlConnection con = new SqlConnection("Data
Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\product.mdf;Integrated
Security=True;Connect Timeout=30"))
        {
            con.Open();
            SqlCommand cmd = new SqlCommand("crudoperations", con);
            cmd.CommandType = CommandType.StoredProcedure;
            if (status == "INSERT")
            {
                cmd.Parameters.AddWithValue("@status",
status);
                cmd.Parameters.AddWithValue("@productname",
productname);
                cmd.Parameters.AddWithValue("@price",
price);
            }
            else if (status == "UPDATE")
            {
                cmd.Parameters.AddWithValue("@status",
status);
                cmd.Parameters.AddWithValue("@productname",
productname);
                cmd.Parameters.AddWithValue("@price",
price);
                cmd.Parameters.AddWithValue("@productid",
productid);
            }
            else if (status == "DELETE")
            {
                cmd.Parameters.AddWithValue("@status",
status);
                cmd.Parameters.AddWithValue("@productid",
productid);
            }
            cmd.ExecuteNonQuery();
            lblresult.ForeColor = Color.Green;
            lblresult.Text = productname + " details " +
status.ToLower() + " successfully.
Başarılı şekilde eklendi!";
            gvDetails.EditIndex = -1;
            BindGridview();
        }
    }
}
Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
<div class="GridviewDiv">
<asp:GridView runat="server" ID="gvDetails" ShowFooter="True" AllowPaging="True" AutoGenerateColumns="False" DataKeyNames="productid,productname" OnPageIndexChanging="gvDetails_PageIndexChanging" OnRowCancelingEdit="gvDetails_RowCancelingEdit"
OnRowEditing="gvDetails_RowEditing" OnRowUpdating="gvDetails_RowUpdating" OnRowDeleting="gvDetails_RowDeleting" OnRowCommand ="gvDetails_RowCommand" BackColor="White" BorderColor="#CC9966" BorderStyle="None" BorderWidth="1px" CellPadding="4" >
    <FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
<HeaderStyle CssClass="headerstyle" BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" />
<Columns>
<asp:BoundField DataField="productid" HeaderText="Product Id" ReadOnly="true" />
<asp:TemplateField HeaderText="Product
Name">
<ItemTemplate>
<asp:Label ID="lblProductname" runat="server" Text='<%# Eval("productname")%>'/>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtProductname" runat="server" Text='<%# Eval("productname")%>'/>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtpname" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText = "Price">
<ItemTemplate>
<asp:Label ID="lblPrice" runat="server" Text='<%# Eval("price")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtProductprice" runat="server" Text='<%# Eval("price")%>'/>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtprice" runat="server" />
<asp:Button ID="btnAdd" CommandName="AddNew" runat="server" Text="Add" />
</FooterTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" ShowDeleteButton="true" />
</Columns>
    <PagerStyle BackColor="#FFFFCC" ForeColor="#330099" HorizontalAlign="Center" />
    <RowStyle BackColor="White" ForeColor="#330099" />
    <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />
    <SortedAscendingCellStyle BackColor="#FEFCEB" />
    <SortedAscendingHeaderStyle BackColor="#AF0101" />
    <SortedDescendingCellStyle BackColor="#F6F0C0" />
    <SortedDescendingHeaderStyle BackColor="#7E0000" />
</asp:GridView>
<asp:Label ID="lblresult" runat="server"></asp:Label>
</div>
</form>
</body>
</html>
Bir makalenin daha sonuna geldik. Bir sonraki makalede
görüşmek üzere. Bahadır ŞAHİN


0 comments:
Yorum Gönder