عملکرد های ایجاد (Insert) ویرایش ,به روز رسانی و حذف در کنترل GridView با ASP.Net
با سلام در این مقاله با یک مثال توضیح خواهیم داد که چگونه عملکردهای ایجاد (Insert) ، ویرایش ، به روز رسانی و حذف را در کنترل GridView به ساده ترین روش ممکن انجام دهید.
این فرآیند همچنین با نام CRUD یعنی ایجاد ، خواندن ، به روزرسانی و حذف در GridView شناخته می شود.
عملیات CRUD بدون استفاده از PostBack با استفاده از jQuery AJAX در ASP.Net انجام خواهد شد.
بانک اطلاعات
از جدول مشتریان با طرح به شرح زیر استفاده کرده ایم.

قبلاً چند رکورد در جدول وارد کرده ایم.

توجه : می توانید جدول بانک اطلاعات SQL را با کلیک روی لینک زیر دانلود کنید.
فایل SQL را بارگیری کنید
کد HTML
کد HTML متشکل از GridView است که در داخل AJAX UpdatePanel قرار داده شده است و دارای چندین رویداد handler است که بعداً مورد بحث قرار می گیرد.
GridView دارای یک ستون CommandField است که دکمه های فرمان یعنی ویرایش ، به روزرسانی ، لغو و حذف را نشان می دهد.
در زیر GridView یک فرم وجود دارد که به ما امکان می دهد داده ها را در جدول پایگاه داده SQL Server وارد کنیم.
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div id="dvGrid" style="padding: 10px; width: 450px">
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowDataBound="OnRowDataBound"
DataKeyNames="CustomerId" OnRowEditing="OnRowEditing" OnRowCancelingEdit="OnRowCancelingEdit" PageSize = "3" AllowPaging ="true" OnPageIndexChanging = "OnPaging"
OnRowUpdating="OnRowUpdating" OnRowDeleting="OnRowDeleting" EmptyDataText="No records has been added."
Width="450">
<Columns>
<asp:TemplateField HeaderText="Name" ItemStyle-Width="150">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%# Eval("Name") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtName" runat="server" Text='<%# Eval("Name") %>' Width="140"></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Country" ItemStyle-Width="150">
<ItemTemplate>
<asp:Label ID="lblCountry" runat="server" Text='<%# Eval("Country") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtCountry" runat="server" Text='<%# Eval("Country") %>' Width="140"></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:CommandField ButtonType="Link" ShowEditButton="true" ShowDeleteButton="true"
ItemStyle-Width="150" />
</Columns>
</asp:GridView>
<table border="1" cellpadding="0" cellspacing="0" style="border-collapse: collapse">
<tr>
<td style="width: 150px">
Name:<br />
<asp:TextBox ID="txtName" runat="server" Width="140" />
</td>
<td style="width: 150px">
Country:<br />
<asp:TextBox ID="txtCountry" runat="server" Width="140" />
</td>
<td style="width: 150px">
<asp:Button ID="btnAdd" runat="server" Text="Add" OnClick="Insert" />
</td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
</div>
فضاهای نام
باید نامهای زیر را وارد کنید.
C #
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
VB.Net
Imports System.Data
Imports System.Configuration
Imports System.Data.SqlClient
اتصال به GridView با سوابق جدول پایگاه داده SQL
GridView از پایگاه داده در داخل رویداد بارگذاری صفحه جمع شده است.
C #
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.BindGrid();
}
}
private void BindGrid()
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
string query = "SELECT * FROM Customers";
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlDataAdapter sda = new SqlDataAdapter(query, con))
{
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Me.BindGrid()
End If
End Sub
Private Sub BindGrid()
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Dim query As String = "SELECT * FROM Customers"
Using con As SqlConnection = New SqlConnection(constr)
Using sda As SqlDataAdapter = New SqlDataAdapter(query, con)
Using dt As DataTable = New DataTable()
sda.Fill(dt)
GridView1.DataSource = dt
GridView1.DataBind()
End Using
End Using
End Using
End Sub
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Me.BindGrid()
End If
End Sub
Private Sub BindGrid()
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Dim query As String = "SELECT * FROM Customers"
Using con As SqlConnection = New SqlConnection(constr)
Using sda As SqlDataAdapter = New SqlDataAdapter(query, con)
Using dt As DataTable = New DataTable()
sda.Fill(dt)
GridView1.DataSource = dt
GridView1.DataBind()
End Using
End Using
End Using
End Sub
درج سوابق در GridView
با کلیک روی Add Button ، رویداد handler زیر اجرا می شود. نام و مقادیر کشور از TextBoxes مربوطه گرفته شده و برای وارد کردن رکورد در پایگاه داده به SQL Query منتقل می شود.
سرانجام باازتباط با روش BindGrid GridView دوباره با داده ها جمع می شود.
C #
protected void Insert(object sender, EventArgs e)
{
string name = txtName.Text;
string country = txtCountry.Text;
txtName.Text = "";
txtCountry.Text = "";
string query = "INSERT INTO Customers VALUES(@Name, @Country)";
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Parameters.AddWithValue("@Name", name);
cmd.Parameters.AddWithValue("@Country", country);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
this.BindGrid();
}
VB.Net
Protected Sub Insert(ByVal sender As Object, ByVal e As EventArgs)
Dim name As String = txtName.Text
Dim country As String = txtCountry.Text
Dim query As String = "INSERT INTO Customers VALUES(@Name, @Country)"
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
txtName.Text = ""
txtCountry.Text = ""
Using con As SqlConnection = New SqlConnection(constr)
Using cmd As SqlCommand = New SqlCommand(query)
cmd.Parameters.AddWithValue("@Name", name)
cmd.Parameters.AddWithValue("@Country", country)
cmd.Connection = con
con.Open()
cmd.ExecuteNonQuery()
con.Close()
End Using
End Using
Me.BindGrid()
End Sub
ویرایش و به روزرسانی سوابق GridView
ویرایش
با کلیک بر روی دکمه ویرایش ، کنترل رویداد OnRowEditing GridView شروع می شود. در اینجا به سادگی EditIndex از GridView با Row Index از GridView Row ویرایش می شود .
C #
protected void OnRowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
this.BindGrid();
}
VB.Net
Protected Sub OnRowEditing(sender As Object, e As GridViewEditEventArgs)
GridView1.EditIndex = e.NewEditIndex
Me.BindGrid()
End Sub
به روز رسانی
با کلیک بر روی دکمه به روزرسانی ، رویداد OnRowUpdating GridView شروع می شود.
CustomerId که کلید اصلی است از ویژگی DataKey GridView گرفته می شود در حالی که قسمت های Name و Country از TextBoxes مربوطه گرفته شده و برای بروزرسانی سوابق در دیتابیس به Query SQL منتقل می شوند.
سرانجام با ارتباط با روش BindGrid GridView دوباره با داده ها جمع می شود.
C #
protected void OnRowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = GridView1.Rows[e.RowIndex];
int customerId = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]);
string name = (row.FindControl("txtName") as TextBox).Text;
string country = (row.FindControl("txtCountry") as TextBox).Text;
string query = "UPDATE Customers SET Name=@Name, Country=@Country WHERE CustomerId=@CustomerId";
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Parameters.AddWithValue("@CustomerId", customerId);
cmd.Parameters.AddWithValue("@Name", name);
cmd.Parameters.AddWithValue("@Country", country);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
GridView1.EditIndex = -1;
this.BindGrid();
}
VB.Net
Protected Sub OnRowUpdating(ByVal sender As Object, ByVal e As GridViewUpdateEventArgs)
Dim row As GridViewRow = GridView1.Rows(e.RowIndex)
Dim customerId As Integer = Convert.ToInt32(GridView1.DataKeys(e.RowIndex).Values(0))
Dim name As String = (TryCast(row.FindControl("txtName"), TextBox)).Text
Dim country As String = (TryCast(row.FindControl("txtCountry"), TextBox)).Text
Dim query As String = "UPDATE Customers SET Name=@Name, Country=@Country WHERE CustomerId=@CustomerId"
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As SqlConnection = New SqlConnection(constr)
Using cmd As SqlCommand = New SqlCommand(query)
cmd.Parameters.AddWithValue("@CustomerId", customerId)
cmd.Parameters.AddWithValue("@Name", name)
cmd.Parameters.AddWithValue("@Country", country)
cmd.Connection = con
con.Open()
cmd.ExecuteNonQuery()
con.Close()
End Using
End Using
GridView1.EditIndex = -1
Me.BindGrid()
End Sub
لغو ویرایش
با کلیک بر روی دکمه Cancel ، رویداد OnRowCancelingEdit GridView handlerشروع می شود. در اینجا EditIndex روی -1 تنظیم شده و GridView با داده جمع شده است.
C #
protected v id OnRowCancelingEdit(object sender, EventArgs e)
{
GridView1.EditIndex = -1;
this.BindGrid();
}
VB.Net
Protected Sub OnRowCancelingEdit(sender As Object, e As EventArgs)
GridView1.EditIndex = -1
Me.BindGrid()
End Sub
حذف سوابق GridView
با کلیک بر روی دکمه Delete ، کنترل رویداد OnRowDeleting GridView شروع می شود.
CustomerId که کلید اصلی است از ویژگی DataKey GridView گرفته می شود و برای حذف فایل از پایگاه داده به Query SQL منتقل می شود.
سرانجام باارتباط از روش BindGrid GridView دوباره با داده ها جمع می شود.
C #
protected void OnRowDeleting(object sender, GridViewDeleteEventArgs e)
{
int customerId = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]);
string query = "DELETE FROM Customers WHERE CustomerId=@CustomerId";
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Parameters.AddWithValue("@CustomerId", customerId);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
this.BindGrid();
}
VB.Net
Protected Sub OnRowDeleting(ByVal sender As Object, ByVal e As GridViewDeleteEventArgs)
Dim customerId As Integer = Convert.ToInt32(GridView1.DataKeys(e.RowIndex).Values(0))
Dim query As String = "DELETE FROM Customers WHERE CustomerId=@CustomerId"
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As SqlConnection = New SqlConnection(constr)
Using cmd As SqlCommand = New SqlCommand(query)
cmd.Parameters.AddWithValue("@CustomerId", customerId)
cmd.Connection = con
con.Open()
cmd.ExecuteNonQuery()
con.Close()
End Using
End Using
Me.BindGrid()
End Sub
به منظور نمایش یک پیام تأیید هنگام حذف سطر ، از رویداد OnRowDataBound , handler استفاده میکنیم که در آن ابتدا دکمه Delete را تعیین و سپس جاوا اسکریپت را تأیید کرده تا درclient side خود کلیک کرده و آن را کنترل کنید.
C #
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowIndex != GridView1.EditIndex)
{
(e.Row.Cells[2].Controls[2] as LinkButton).Attributes["onclick"] = "return confirm('Do you want to delete this row?');";
}
}
VB.Net
Protected Sub OnRowDataBound(sender As Object, e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow AndAlso e.Row.RowIndex <> GridView1.EditIndex Then
TryCast(e.Row.Cells(2).Controls(2), LinkButton).Attributes("onclick") = "return confirm('Do you want to delete this row?');"
End If
End Sub
صفحه بندی
با کلیک بر روی شماره صفحه ، رویداد OnPageIndexChanging شروع می شود. در اینجا ، ویژگی PageIndex از GridView به روز می شود.
سرانجام با ارتباط از روش BindGrid GridView دوباره با داده ها جمع می شود.
C #
protected void OnPaging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
this.BindGrid();
}
VB.Net
Protected Sub OnPaging(ByVal sender As Object, ByVal e As GridViewPageEventArgs)
GridView1.PageIndex = e.NewPageIndex
Me.BindGrid()
End Sub
نمایش AJAX Loader در حین افزودن ، ویرایش ، بروزرسانی ، حذف و صفحه بندی
پلاگین jQuery BlockUI در dvGrid HTML DIV اعمال شده است. وقتی AJAX UpdatePanel درخواستی را انجام می دهد ، HTML DIV مسدود شده و یک انیمیشن نمایش داده می شود.
پس از اتمام درخواست ، HTML DIV از حالت انسداد خارج شده و انیمیشن پنهان می شود.
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="scripts/jquery.blockUI.js"></script>
<script type="text/javascript">
$(function () {
BlockUI("dvGrid");
$.blockUI.defaults.css = {};
});
function BlockUI(elementID) {
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_beginRequest(function () {
$("#" + elementID).block({ message: '<div align = "center">' + '<img src="images/loadingAnim.gif"/></div>',
css: {},
overlayCSS: { backgroundColor: '#000000', opacity: 0.6, border: '3px solid #63B2EB' }
});
});
prm.add_endRequest(function () {
$("#" + elementID).unblock();
});
};
</script>