در این مقاله خواهیم آموخت که چگونه میتوان یک مورد را با استفاده از رویداد RowCommand حذف کرد.این آموزش در محیط ASP.NET وزبان سی شارپ مورد برسی قرار گرفته است که در ابزار دیتاگرید توسط رویدادRowCommand نسبت به حذف اقدام کنید. با من در این مقاله همراه باشید …
نکاتی درباره ی رویداد RowCommand
RowCommand یکی از رویداد های GridView است.
این رویداد با کلیک در داخل GridView اجرا میشود.
برای اجرای هر نوع عملیاتی با rowcommand در GridView باید از یک property به نام commandname استفاده کنیم.
مشخصات CommandName برای یک کنترل button استفاده میشود.
مثال : commandname=”abc” .
در خط بالا abc یک commandname است.
استفاده از commandname در itemtemplate برای button در زیر آورده شده است.
حال چرا CommandName ؟
CommandName برای ایجاد تفاوت بین کنترل نوع دو button در یک GridView استفاده میشود که در زیر آورده شده است :
برای قطعه کد بالا Design زیر را خواهیم داشت :
کد :
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; namespace WebApplication1 { public partial class WebForm2 : System.Web.UI.Page { SqlConnection con = new SqlConnection("server=.;database=abc;trusted_connection=true"); protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { bind(); } } public void bind() { SqlCommand cmd = new SqlCommand("select * from employee", con); SqlDataAdapter da = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); da.Fill(ds, "con"); GridView1.DataSource = ds; GridView1.DataBind(); } protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e) { if (e.CommandName == "comdel") { int l = Convert.ToInt32(e.CommandArgument); con.Open(); SqlCommand cmd = new SqlCommand("delete from employee where eno=@a", con); cmd.Parameters.AddWithValue("@a", l); int i = cmd.ExecuteNonQuery(); if (i == 1) { Response.Write("Record deleted"); bind(); } else { Response.Write("Recodrd not deleted..."); } Page_Load(sender, e); } } } }
توضیحاتی در رابطه با e.commandargument :
در قطعه کد بالا من از خط های زیر در رویداد rowcommand استفاده کرده ام.
if (e.CommandName == "comdel") { int l = Convert.ToInt32(e.CommandArgument); ….. … … }
e.commandargument شماره ی کارمند را مشخص میکند. صفحه ی aspx را را میتوانید در شکل زیر مشاهده کنید :
لطفا نظرات و پیشنهاداتتون رو با من درمیان بگذارید.
موفق باشید !
هیچ دیدگاهی نوشته نشده است.