DataGrid implementation to delete (with prompt) to change the paging

xiaoxiao2021-03-06  44

Maybe everyone will say, there are many articles on the Internet, including Mencius, why should I write again? I think we are not only to achieve, but more need to understand. The following first post code and then analyze some of the key code.

Database table name: TB1, 3 fields, respectively, from self-increasing primary keys, VName Varchar (50), IAGE INT (The following code does not do any error capture processing) Front desk <% ... @ page language = "C # "Codebehind =" Webform5.aspx.cs "autoeventwireup =" false "inherits =" 9cbs.webform5 "%> WebForm5 </ title> <meta content = "Microsoft Visual Studio .NET 7.1" Name = "Generator"> <meta content = "c #" name = "code_language"> <meta content = "javascript" name = " VS_DEFAULTCLIENTScript "> <meta content =" http://schemas.microsoft.com/intellisense/ie5 "name =" vs_targetschema "> </ head> <body> <form id =" form1 "method =" post "runat =" Server> <asp: textbox id = "textbox1" runat = "server" width = "88px"> </ ask: textBox> <ask: textbox id = "textbox2" runat = "server" width = "40px"> < / asp: textbox> <ask = "Button1" runat = "server" text = "Add"> </ asp: button> <ask: DataGrid ID = "DataGrid1" runat = "server" autogeneratecolumns = "false" DataKeyfield = "ID" allowpaging = "TR UE "Pagesize =" 5 "onEDitcommand =" edit "oncancelcommand =" cancel "onupdateCommand =" update "> <columns> <ask: templatecolumn headertext =</p> <p>"Name"> <itemtemplate> <% ... # databinder.eval (container.dataitem, "vname")%> </ itemtemplate> <edititemtemplate> <asp: textbox id = "name" runat = "server" text = '<% # Databinder.eval (container.dataitem, "vname")%>' width = "88px"> </ asp: textbox> </ adj: TemplateColumn> <ask: templateColumn headertext = "age" > <Itemtemplate> <% ... # databinder.eval (container.DataItem, "IAGE")%> </ itemtemplate> <edititemtemplate> <asp: textbox id = "agn" runat = "server" text = '<% # DataBinder.eval (Container.DataItem, "IAGE")%> 'Width = "40px"> </ asp: textbox> </ edititemtemplate> </ ask: templateColumn> <Asp: EditCommandColumn UpdateText = "update" CancelText = "cancel" EditText = "edit"> </ asp: EditCommandColumn> <asp: ButtonColumn Text = "delete" CommandName = "del"> </ asp: ButtonColumn> </ Columns > <PagersTyle Mode = "NumericPages"> </ PagersTyle> </ asp: DataGrid> </ form> </ body> </ html> Background USING SYSTEM;</p> <p>using System.Collections; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Web; using System.Web.SessionState; using System.Web.UI; using System.Web .Ui.webcontrols; using system.web.ui.htmlControls; Namespace 9cbs ... {/ ** //// <summary> /// WebForm5 summary description. /// </ summary> public class WebForm5: System.Web.UI.Page ... {protected System.Web.UI.WebControls.TextBox TextBox1; protected System.Web.UI.WebControls.TextBox TextBox2; protected System.Web .Ui.webcontrols.button button1; protected system.web.ui.webControls.DataGrid DataGrid1; Private Void Page_load (Object Sender, System.EventArgs E) ... {// Place user code here to initialize page if (! IsPostBack) ... {SetBind ();}} protected void SetBind () ... {SqlConnection conn = new SqlConnection (System.Configuration.ConfigurationSettings.AppSettings [ "conn"]); SqlDataAdapter da = new SqlDataAdapter ( "select * From TB1 ", CONN); DataSet DS = New Dataset (); DA.FILL (DS," Table1 "); this.dataGrid1.datasource = DS.TABLES [" Table1 "]; this.dataGrid1.databind ();} Web Form Designer Generated Code #Region Web Form Designer Generated Code Override Protected Void OnInit (Eventargs E) ... {/// Codegen: This call is required for the ASP.NET Web Form Designer. // InitializeComponent (); base.oninit (e);} / ** //// <summary> /// Designer supports the required method - do not use the code editor to modify the // / this method.</p> <p>/// </ summary> private void InitializeComponent () ... {this.Button1.Click = new System.EventHandler (this.Button1_Click); this.DataGrid1.ItemCreated = new System.Web.UI.WebControls.DataGridItemEventHandler (this.DataGrid1_ItemCreated); this.DataGrid1.ItemCommand = new System.Web.UI.WebControls.DataGridCommandEventHandler (this.DataGrid1_ItemCommand); this.DataGrid1.PageIndexChanged = new System.Web.UI.WebControls.DataGridPageChangedEventHandler (this.DataGrid1_PageIndexChanged ); this.Load = new System.EventHandler (this.Page_Load);} #endregion private void Button1_Click (object sender, System.EventArgs e) ... {SqlConnection conn = new SqlConnection (System.Configuration.ConfigurationSettings.AppSettings [ "conn"]); SQLCOMMAND Comm = New SQLCOMMAND ("INSERT INTO TB1 (IAGE) VALUES (@ vname, @ iAGE)", conn; sqlparameter parm1 = new SQLParameter ("@ vname", sqldbtype. NVARCHAR, 50); PARM1.VALUE = this.textBox1.text; sqlparameter parm2 = new SQLParameter ("@ iAGe", sqldbtype.int); parm2.value = this.textBox2.text; comm.parameters.add (PARM1); comm.Parameters.Add (parm2); conn.Open (); comm.ExecuteNonQuery (); conn.Close (); SetBind ();} private void DataGrid1_ItemCommand (object source, System.Web.UI.WebControls.DataGridCommandEventArgs e) ... {if (e.commandname == "DEL") ... {SQLConnection conn =</p> <p>new SqlConnection (System.Configuration.ConfigurationSettings.AppSettings [ "conn"]); SqlCommand comm = new SqlCommand ( "delete from tb1 where ID = @ id", conn); SqlParameter parm1 = new SqlParameter ( "@ id", SqlDbType. Int); parm1.value = this.dataGrid1.datakeys [E.Item.itemindex]; Comm.Parameters.Add (PARM1); conn.Open (); comm.executenon query (); conn.close (); setbind () ;}} private void DataGrid1_PageIndexChanged (object source, System.Web.UI.WebControls.DataGridPageChangedEventArgs e) ... {this.DataGrid1.CurrentPageIndex = e.NewPageIndex; SetBind ();} protected void edit (object sender, DataGridCommandEventArgs e) ... {this.DataGrid1.edititeMindex = E.Item.itemindex; setbind ();} protected (}) ... {this.DataGrid1.ed itItemIndex = -1; SetBind ();} protected void update (object sender, DataGridCommandEventArgs e) ... {SqlConnection conn = new SqlConnection (System.Configuration.ConfigurationSettings.AppSettings [ "conn"]); SqlCommand comm = new SqlCommand ( "Update TB1 set vname = @ vname, IAGE = @ IAGE WHERE ID = @ ID", conn; sqlparameter parm1 = new SQLParameter ("@ vname", sqldbtype.nvarchar, 50); parm1.value = ((TextBox) E .Item.FindControl ("name")). Text; sqlparameter parm2 = new sqlparameter ("@ iAGe", sqldbtype.int); parm2.value =</p> <p>((TextBox) E.Item.FindControl ("age")). Text; sqlparameter PARM3 = New SqlParameter ("@ id", sqldbtype.int); Parm3.Value = this.DataGrid1.DataKeys [E.Item.ItemIndex] Comm.Parameters.Add (PARM1); Comm.Parameters.Add (PARM2); Comm. Parameters.Add (PARM3); conn.ExecutenonQuery (); conn.close (); this.DataGrid1. EditItemIndex = -1; SetBind ();} private void DataGrid1_ItemCreated (object sender, System.Web.UI.WebControls.DataGridItemEventArgs e) ... {foreach (DataGridItem di in this.DataGrid1.Items) ... {if (di .ItemType == ListiteMTYPE.ITEM || Di.ItemType == ListiteMTYPE.AlternatingItem || Di.ItemType == ListItemType.editItem) ... {(LinkButton) Di.cells [3] .controls [0]). Attributes .Add ("onclick", "Return Confirm ('delete?');");}} // generally not written, see the sixth point}} (1) You can see some of Setbind () Code, no Explicitly open and close SqlConnection but the code is actually operating because the Fill method of SqlDataAdqper is automatically turned on or off (of course, it will detect whether it is connected, if the words have been opened, no error is turned on). (2) Take a look at the if (! Ispostback) {setbind ();} Many beginners don't understand the blindness of ISPostback blindly or does not add this sentence. In fact, add your needs ISPostback is true It means that the page is not the first timeload is also the case of returning. It is only when it! Ispostback is really time to use setbind (); that is, the key to the binding DataGrid is that we need to modify the record, this is often a lot of netizens in modifying records. When it is found to be written to the database or the content in the original TextBox.</p> <p>Why is this so? When you modify, we press the "Edit" button to execute the code inside Protected Void Edit (Object Sender, DataGridCommandeventArgs E). After modifying the data in TextBox, we press the "Update" button, this time is a Postback If there is no if (! Ispostback), the binding code is executed once, that is, the TEXTBOX among the template columns is re-assigned, then go to the code in Protected Void Update (Object Sender, DataGridCommandeventArgs E), you The code is executed, but ((textbox) E.Item.FindControl ("name")). Text is not your modified thing but the original thing. (3) Modified code PARM3.Value = this.dataGrid1.datakeys [E.Item.itemindex] For E.Item.ItemIndex is a clicked this line (the row of event triggers), if you want to use this as the primary key To put it in the WHERE clause Update or delete is obviously unsuitable, such as the third line, the primary key of this record in the database is 20 or characters, so we need to specify a DataKeyField for DataGrid (front code) Tell it, my primary key is this field, in the binding DataGrid's DataKeys stores the primary key of each record in the list control, so use index this.DataGrid1.DataKeys [E.Item.ItemIndex 】 You can get the primary key (4) to see some of the code in Private Void DataGrid1_ItemCreated (Object Sender, System.Web.ui.WebControls.DataGriditeMeventArgs E), first iTemcreated This event is when you create an item in the DataGrid control The server happened, there is no binding data at this time, so if you get the value in the DataGrid in this itemcreated, you can't get it.</p> <p>foreach (DataGridItem di in this.DataGrid1.Items) {if (di.ItemType == ListItemType.Item || di.ItemType == ListItemType.AlternatingItem || di.ItemType == ListItemType.EditItem) {((LinkButton) di. Cells [3] .controls [0]). Attributes.add ("onclick", "Return Confirm ('delete?');"); // The type here is converted to linkButton, when not specified ButtonColumn's Buttype, the default Is LinkedButton, if specified as PushButton, here the type conversion should write button instead of linkbutton, otherwise, this code will increase the client's Click event, when all DataGrid1.Items, when we pay, only You need to add properties to the first button control (Controls [0]) in the column 4 (Cells [3]) in ListItemType.ItemType.alternatingItem, because this is not found in the DataGrid's header or Footer. Delete buttons (although they are DataGrid1.Items). Imagine how if you don't write Di.ItemType == ListItemType.Edititem? The result is that when edited, press to delete it at that time, there is no prompt, because the button does not give the edited row plus the script. When you want to talk about this process, you may not want to delete an operation when you edit (That is, click the Edit button but did not click cancel or update the button "is not running), the improved method is very simple: Change the E.CommandName == "DEL" to E.CommandName == "DEL" && E.Item.itemType! = ListiteMTYPE.EDITEM, you can achieve this. It is also not used here (linkButton) Di.cells [3] .FindControl (ID)) to find this button is because this button is not written <asp: buttoncolumn text = "COMMANDNAME = "DEL"> </ ask: buttoncolumn> cannot be added, if this button is placed in the template column, you can have ID. (5) THISDATAGRID1.EDITEMINDEX = EITAGRID1.EDITITEX = ETEM.ItemIndex during editing This.DataGrid1.editItemIndex = -1 When EditIndex! = - 1, the DataGrid displayed is no longer iTemTemplate. Things but eDititemtemplate, so when you set -1 when canceling editing, the same EditIndEx and ItemIndex are almost numbered from 0, indicating the index number of the edited line.</p> <p>(6) foreach (DataGridItem di in this.DataGrid1.Items) {if (di.ItemType == ListItemType.Item || di.ItemType == ListItemType.AlternatingItem || di.ItemType == ListItemType.EditItem) {((LinkButton ) Di.cells [3] .controls [0]). Attributes.add ("onclick", "Return Confirm ('delete?');");}}} This code I don't tell ItemType if ITEMTYPE Error, so it is looped to DataGrid1.items (you can see if you have DataGrid1.Items.count> Pagesize after setting FOOTER), in general, you can write if you can write if (E.Item.itemType == ListitemType.Item || E.Item.itemType == ListItemType.AlternatingItem || E.Item.itemType == ListiteMTYPE.EDITITEM) {(LinkButton) E.Item.cells [3] .controls [0]). Attributes. Add ("onclick", "Return Confirm ('delete?');");} Team first, first talk, continue to add. How to implement code analysis - DataGrid implements self-amplification, radio, multiple choice</p> <p>Please see http://blog.9cbs.net/lovecherry/archive/2005/03/01/306243.aspx</p> <p>All code here http://blog.9cbs.net/loveCherry/archive/2005/03/01/306278.aspx</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-47604.html</div><div class="plugin d-flex justify-content-center mt-3"></div><hr><div class="row"><div class="col-lg-12 text-muted mt-2"><i class="icon-tags mr-2"></i><span class="badge border border-secondary mr-2"><h2 class="h6 mb-0 small"><a class="text-secondary" href="tag-2.html">9cbs</a></h2></span></div></div></div></div><div class="card card-postlist border-white shadow"><div class="card-body"><div class="card-title"><div class="d-flex justify-content-between"><div><b>New Post</b>(<span class="posts">0</span>) </div><div></div></div></div><ul class="postlist list-unstyled"> </ul></div></div><div class="d-none threadlist"><input type="checkbox" name="modtid" value="47604" checked /></div></div></div></div></div><footer class="text-muted small bg-dark py-4 mt-3" id="footer"><div class="container"><div class="row"><div class="col">CopyRight © 2020 All Rights Reserved </div><div class="col text-right">Processed: <b>0.034</b>, SQL: <b>9</b></div></div></div></footer><script src="./lang/en-us/lang.js?2.2.0"></script><script src="view/js/jquery.min.js?2.2.0"></script><script src="view/js/popper.min.js?2.2.0"></script><script src="view/js/bootstrap.min.js?2.2.0"></script><script src="view/js/xiuno.js?2.2.0"></script><script src="view/js/bootstrap-plugin.js?2.2.0"></script><script src="view/js/async.min.js?2.2.0"></script><script src="view/js/form.js?2.2.0"></script><script> var debug = DEBUG = 0; var url_rewrite_on = 1; var url_path = './'; var forumarr = {"1":"Tech"}; var fid = 1; var uid = 0; var gid = 0; xn.options.water_image_url = 'view/img/water-small.png'; </script><script src="view/js/wellcms.js?2.2.0"></script><a class="scroll-to-top rounded" href="javascript:void(0);"><i class="icon-angle-up"></i></a><a class="scroll-to-bottom rounded" href="javascript:void(0);" style="display: inline;"><i class="icon-angle-down"></i></a></body></html><script> var forum_url = 'list-1.html'; var safe_token = 'CzwYnQAVh12DIj6Um6yqUNTe4grbrtnauUNACHVq4gv0_2Bp5gQpouSK638PIybnjUbBkBewgtdUPGoNa_2Fkkntzg_3D_3D'; var body = $('body'); body.on('submit', '#form', function() { var jthis = $(this); var jsubmit = jthis.find('#submit'); jthis.reset(); jsubmit.button('loading'); var postdata = jthis.serializeObject(); $.xpost(jthis.attr('action'), postdata, function(code, message) { if(code == 0) { location.reload(); } else { $.alert(message); jsubmit.button('reset'); } }); return false; }); function resize_image() { var jmessagelist = $('div.message'); var first_width = jmessagelist.width(); jmessagelist.each(function() { var jdiv = $(this); var maxwidth = jdiv.attr('isfirst') ? first_width : jdiv.width(); var jmessage_width = Math.min(jdiv.width(), maxwidth); jdiv.find('img, embed, iframe, video').each(function() { var jimg = $(this); var img_width = this.org_width; var img_height = this.org_height; if(!img_width) { var img_width = jimg.attr('width'); var img_height = jimg.attr('height'); this.org_width = img_width; this.org_height = img_height; } if(img_width > jmessage_width) { if(this.tagName == 'IMG') { jimg.width(jmessage_width); jimg.css('height', 'auto'); jimg.css('cursor', 'pointer'); jimg.on('click', function() { }); } else { jimg.width(jmessage_width); var height = (img_height / img_width) * jimg.width(); jimg.height(height); } } }); }); } function resize_table() { $('div.message').each(function() { var jdiv = $(this); jdiv.find('table').addClass('table').wrap('<div class="table-responsive"></div>'); }); } $(function() { resize_image(); resize_table(); $(window).on('resize', resize_image); }); var jmessage = $('#message'); jmessage.on('focus', function() {if(jmessage.t) { clearTimeout(jmessage.t); jmessage.t = null; } jmessage.css('height', '6rem'); }); jmessage.on('blur', function() {jmessage.t = setTimeout(function() { jmessage.css('height', '2.5rem');}, 1000); }); $('#nav li[data-active="fid-1"]').addClass('active'); </script>