欢迎光临
我们一直在努力

DataGrid常见解决方案(三)–在DataGrid中选择,确认,删除多行复选框列表-.NET教程,VB.Net语言

建站超值云服务器,限时71元/月

在datagrid中选择,确认,删除多行复选框列表

selecting, confirming & deleting multiple checkbox items in a datagrid (i.e. hotmail & yahoo)

introduction

although i dont have either a hotmail or yahoo email account, i do have friends that do, and i have often seen them check their e-mail and noticed how it was all neatly displayed in a table. right next to each item in their e-mail table was a simple little checkbox. at the bottom or top of this table you would have another checkbox giving them the ability to select all of the e-mail, and a button to submit back. once this was done they would receive a nice popup alert to confirm whats about to happen, and then once this is ok ed, boom, all the selected items are deleted.

.net, of course, has the datagrid, their finest and most popular control to date, and it should be pretty easy to get the same functionality, right? well, not quite. doing this with .net is not that straightforward and functional as i wouldve liked it to be. sure its quite easy to add an edit / update button or link to each row and even a delete button to each, alongside a pop up alert as well! however, applying this delete feature to each and every button and deleting them one by one is a little maddening. nor is the datagrid set up in allowing a way of adding a main "select all" checkbox to easily select all of the boxes, and then applying any particular action.

in this article, we will examine how to create a fully functional datagrid with all the features youd find set up on hotmail or yahoo. as an added bonus well be performing all of our data tasks strictly utilizing microsofts new data access application block or daab v2. to any who may feel a little behind with daab, have no fear, everything here can still be accomplished with pre-daab data objects as the only difference here is the data access part of it. trust me there is a huge difference between the two, for one daab enable you to write about 75% less code that you would normally need when compared with regular ado.net!

so, before we begin, download the daab dll from the above link, install it, and copy it into you application’s bin folder and youre ready to go. also, be sure and take a peek at the daab documentation that came with your installation for an overview and any questions you may have.

ok, lets get to it then.

our fully-featured datagrid

selecting & deleting multiple items will definitely be set up quite differently than any other type of .net datagrid deleting you probably have seen. however, well still follow the same logical flow of deletion, and well still confirm any delete actions about to take place after we have selected all our items. much of the magic in making this work is really going to come from client-side javascript, that is ultimately responsible for wiring up our main "select all" checkbox to handle the selecting and deselecting of our checkboxes. also, included is our server-side delete method that erases our data, and a datagrid refresher method to rebind our datagrid after we have completed our data deletion.

have a look at figure 1 to get an idea of what your datagrid will look like:

figure 1

here is the code to set up our datagrid:

<form runat="server">

<h3>selecting, confirming & deleting multiple checkbox items in a datagrid (i.e. hotmail & yahoo)</h3>

<br>

<asp:datagrid id="mydatagrid" runat="server"

width="700"

backcolor="white"

bordercolor="black"

cellpadding=3

cellspacing="0"

font-size="9pt"

autogeneratecolumns="false"

headerstyle-backcolor="darkred"

headerstyle-forecolor="white"

>

<columns>

<asp:templatecolumn>

<headertemplate>

<asp:checkbox id="checkall" onclick="javascript: return select_deselectall (this.checked, this.id);" runat="server"/>

<font face="webdings" color="white" size="4">a</font>

</headertemplate>

<itemtemplate>

<asp:checkbox id="deletethis" onclick="javascript: return select_deselectall (this.checked, this.id);" runat="server"/>

</itemtemplate>

</asp:templatecolumn>

// … rest of our custom template & bound columns

</columns>

</form>

the code listed above is what makes our datagrid set up behave just like the grids on hotmail and yahoo. our .net datagrid will have the same functionality and options available for selecting however many items, or perhaps all, that youd like to delete, and once you do and submit, kiss them goodbye.

datagrid setup

the first step towards creating this functionality is to begin by adding a new datagrid column (either before or after our main data, it doesnt matter) thatll contain our individual checkboxes, but also include our main top "select all" checkbox (if and when we need to select and deselect all the checkboxes below it). to do this we first make sure our datagrids autogeneratecolumns property is set to false, since were going to create the necessary custom header and item templates, alongside our necessary boundcolumns, within our datagrid columns section (that can be customized and could contain whatever you need them to).

the only important thing to notice here, regarding our objective, is our first templatecolumn that contains our checkboxes. the main focal point with this whole application rests solely on this first template column and its two sub templates: headertemplate and itemtemplate. each contain the necessary checkboxes, both are wired to onclick events that executes select_deselectall (our super-slick client-side javascript method) when either checkbox is checked, and in turn are fully responsible for giving us all the great functionality ive spoken of. incidentally, the webdings fonts lowercase letter "a" give us our check symbol.

selecting and de-selecting our checkboxes

now that both checkboxes are wired to our multi-faceted javascript method, how is that one function going to determine the checkbox its dealing with, and the action it needs to carry out? ah, heres how 🙂

our function select_deselectall, listed below, accepts two arguments: the checkboxs checked value, and its id. once this function is called, and its two arguments have been passed in, itll begin looping through our form. next, it begins performing some conditional checking utilizing javascripts indexof method to locate the appropriate checkbox, and is based on both the values passed in, which it turn ultimately will give us one of several causes and effects:

if the main "select all" checkbox is checked, it will select all of the datagrid checkboxes

if the main "select all" checkbox is unchecked, then all of the datagrid checkboxes get unselected

finally, if after the main "select all" checkbox is selected and all of the datagrids checkboxes are all checked, any one of those checkboxes gets unchecked, then the main checkbox is also unchecked. this way we dont end up having our checkboxs logic behaving inconsistently or erratically.

function select_deselectall (chkval, idval) {

var frm = document.forms[0];

// loop through all elements

for (i=0; i<frm.length; i++) {

// look for our header templates checkbox

if (idval.indexof (checkall) != -1) {

// check if main checkbox is checked, then select or deselect datagrid checkboxes

if(chkval == true) {

frm.elements[i].checked = true;

} else {

frm.elements[i].checked = false;

}

// work here with the item templates multiple checkboxes

} else if (idval.indexof (deletethis) != -1) {

// check if any of the checkboxes are not checked, and then uncheck top select all checkbox

if(frm.elements[i].checked == false) {

frm.elements[1].checked = false; //uncheck main select all checkbox

}

}

}

}

figure 2 shows you the effect of the javascript above interacting with the datagrid when selecting the top main "select all" checkbox.

figure 2

now, aside from this function allowing a quick full selection, you also have the option of manually selecting as many checkbox items as you wish. next comes the tricky part in how to determine which ones were selected, and how to confirm this the instant you submit the form, and prior to actual deletion.

confirming multiple deletes

in this section, well examine how to confirm multiple deletes when we submit our form. below in figure 3 you can now see the alert confirmation after selecting a couple of items, and then submitting the form by press the "delete items" button. the alert takes place at any time you submit the form (as long as you have more than one checkbox selected).

figure 3

note that this confirmation will alert with all checkboxes selected or a just a few as shown. pressing the delete items button with none selected will not prompt any alert. here now is how we determine what checkboxes are actually checked.

the first thing we did was set up our delete button at the end of our datagrid; just a regular asp server button. we also wired a server-side event to it – delete store – that, when confirmed, will delete the records:

<asp:button text="delete items" onclick="deletestore" id="confirm" runat="server" />

but how does that pop-up alert confirmation appear? well, thats the cool thing. we get this by adding the code listed below to our button server control as soon as the page loads, in our page_load method, by locating it using the findcontrol method and then adding to the button attributes, like so:

webcontrol button = (webcontrol) page.findcontrol("confirm");

button.attributes.add ("onclick", "return confirmdelete (this.form);");

so, the second the page loads, it attached the javascript handler to this button, and if you examine the html source code, the button afterwords, actually looks like this:

<input type="submit" name="confirm" value="delete items" id="confirm" onclick="return confirmdelete (this.form);" />

cool huh? now, the second this button is pressed, is when it can now trigger the client side javascript function below:

function confirmdelete (frm) {

// loop through all elements

for (i=0; i<frm.length; i++) {

// look for our checkboxes only

if (frm.elements[i].name.indexof(deletethis) !=-1) {

// if any are checked then confirm alert, otherwise nothing happens

if(frm.elements[i].checked) {

return confirm (are you sure you want to delete your selection(s)?)

}

}

}

}

ok, what happening here? well, the js function above is, for all intents and purposes, not that different from the previous javascript function – "select_deselectall." except, instead of determining if the main "select all" checkbox is checked, it actually checks to see whether if any of the datagrid row checkboxes are checked. if so, itll then, and only then, alert you with a confirmation to proceed onto either to delete or cancel.

deleting data

now recall our asp:button above, and its default javascript onclick event handler attached on page_load. aside from this we also notice it has another onclick event (this one being server based) that gets raised when the button is clicked, rather pressed, thatll allow it to fire the server-side deletestore method to delete our data:

public void deletestore (object sender, eventargs e) {

string dgids = "";

bool bxschkd = false;

foreach (datagriditem i in mydatagrid.items) {

checkbox deletechkbxitem = (checkbox) i.findcontrol ("deletethis");

if (deletechkbxitem.checked) {

bxschkd = true;

// concatenate datagrid item with comma for sql delete

dgids += ((label) i.findcontrol ("storeid")).text.tostring() + ",";

}

}

// set up sql delete statement, using lastindexof to remove tail comma from string.

string deletesql = "delete from stores where stor_id in (" + dgids.substring (0, dgids.lastindexof (",")) + ")";

if (bxschkd == true) { // execute sql query only if checkboxes are checked, otherwise error occurs with initial null string

try {

sqlhelper.executenonquery (objconnect, commandtype.text, deletesql);

outputmsg.innerhtml += "<font size=4><b>store information has been deleted.</b></font>";

outputmsg.style["color"] = "green";

} catch (sqlexception err) {

outputmsg.innerhtml += err.message.tostring(); //"<font size=4><b>an error occurred and the record could not be deleted</b></font>";

outputmsg.style["color"] = "red";

}

//refresh data

binddata();

}

}

since having wired the two client/server methods together, its our javascript code that actually intercepts this buttons call and goes first. if you confirm ok, then will the deleting server-side method execute, otherwise itll cancel all events after that point and prevent anything from posting back.

looking at the deletestore() method, youll notice that it is actually does a few things. first, it sets up the string variable "dgids" that will hold all of our selected datagrid ids. next, it loops through the datagrid, and gathers all of the selected item ids that are based on the rows templatecolumn id, which is why i kept the id control as a templatecolumn and the rest boundcolumns as these types of controls do not support the id property we need for referencing our data. after this, it will, upon verifying checked items, gather all the ids and assign them to our "dgids" variable, thatll be used with our sql "deletesql" delete statement.

the "deletesql" delete statement uses the "where in" argument to perform the multiple deletes in one shot. since we need to separate each id with a comma, youll notice that in the loop i attach a comma after each collected item. this way well have all of our items clearly defined in our sql. one problem however is that since we add on a comma after each collected item, the last one as well will include a tail-end comma and sql wont like this. for example, once we loop through the datagrid, gather up all of the selected items, and assign it to our delete string we could end up with something like this:

delete from stores where stor_id in (2,4,6,7,)

notice the last comma; thats a no-no. to quickly and easily remedy this, we must remove the last comma, and we do this by pulling the substring we need from the "dgids" string using lastindexof (",") effectively removing the last comma, and properly formatting the delete statement for sql, like so:

delete from stores where stor_id in (2,4,6,7)

finally, deletestore proceeds to execute the query against the database. incidentally, for those wondering why i have a conditional with bxschkd? well its because if i dont initially select any items, im returned an error on page_load due to our sqlhelper having nothing initialized. therefore, by do so, our deletestore method will remain silent, and happily waiting in the wings until it does get the actual go ahead.

so thats the crux of our datagrid application, and technology behind doing multiple checkbox deletes a la hotmail and yahoo style. and on that note, heres all the code. just have sql server ready, daab installed, then cut and paste the code below, and have fun.

heres our main page code:

<%@ page language="c#" debug="false" strict="true" explicit="true" inherits="multideletedg.webform" src="mdatagrid.aspx.cs"%>

<html>

<body>

<form runat="server">

<h3>selecting, confirming & deleting multiple checkbox items in a datagrid (i.e. hotmail & yahoo)</h3>

<br>

<asp:datagrid id="mydatagrid" runat="server"

width="700"

backcolor="white"

bordercolor="black"

cellpadding=3

cellspacing="0"

font-size="9pt"

autogeneratecolumns="false"

headerstyle-backcolor="darkred"

headerstyle-forecolor="white"

>

<columns>

<asp:templatecolumn>

<headertemplate>

<asp:checkbox id="checkall" onclick="javascript: return select_deselectall (this.checked, this.id);" runat="server"/>

<font face="webdings" color="white" size="4">a</font>

</headertemplate>

<itemtemplate>

<asp:checkbox id="deletethis" onclick="javascript: return select_deselectall (this.checked, this.id);" runat="server"/>

</itemtemplate>

</asp:templatecolumn>

<asp:templatecolumn>

<headertemplate>id</headertemplate>

<itemtemplate>

<asp:label id="storeid" text=<%# databinder.eval (container.dataitem, "id") %> runat="server"/>

</itemtemplate>

</asp:templatecolumn>

<asp:boundcolumn headertext="store" datafield="store" runat="server"/>

<asp:boundcolumn headertext="address" datafield="address" runat="server"/>

<asp:boundcolumn headertext="city" datafield="city" runat="server"/>

<asp:boundcolumn headertext="state" datafield="state" runat="server"/>

<asp:boundcolumn headertext="zip" datafield="zip" runat="server"/>

</columns>

</asp:datagrid>

<br>

<asp:button text="delete items" onclick="deletestore" id="confirm" runat="server" />

<span id="outputmsg" enableviewstate="false" runat="server"/>

</form>

</body>

and our multideletedg.webform code-behind file – mdatagrid.aspx.cs:

using system;

using system.data;

using system.data.sqlclient;

using system.web;

using system.web.ui;

using system.web.ui.webcontrols;

using system.web.ui.htmlcontrols;

//import daab dll namespace

using microsoft.applicationblocks.data;

namespace multideletedg

{

/// <summary>

/// selecting, confirming & deleting multiple checkbox items in a datagrid (i.e. hotmail & yahoo)

/// author: dimitrios markatos – dmarko1@aol.com

/// date: 8/2003

/// </summary>

public class webform : system.web.ui.page //inherit page class

{

protected system.web.ui.webcontrols.datagrid mydatagrid;

protected system.web.ui.htmlcontrols.htmlgenericcontrol outputmsg; //span tag

protected sqlconnection objconnect;

public void page_load (object sender, eventargs e) {

//implement client side javascript code

string jsscript = "<script language=javascript> \n" +

"<!–\n" +

"function confirmdelete (frm) {\n\n" +

" // loop through all elements\n" +

" for (i=0; i<frm.length; i++) {\n\n" +

" // look for our checkboxes only\n" +

" if (frm.elements[i].name.indexof (deletethis) !=-1) {\n" +

" // if any are checked then confirm alert, otherwise nothing happens\n" +

" if(frm.elements[i].checked) {\n" +

" return confirm (are you sure you want to delete your selection(s)?)\n" +

" }\n" +

" }\n" +

" }\n" +

"}\n\n\n" +

"function select_deselectall (chkval, idval) {\n" +

"var frm = document.forms[0];\n" +

"// loop through all elements\n" +

" for (i=0; i<frm.length; i++) {\n" +

" // // look for our header templates checkbox\n" +

" if (idval.indexof (checkall) != -1) {\n" +

" // check if main checkbox is checked, then select or deselect datagrid checkboxes \n" +

" if(chkval == true) {\n" +

" frm.elements[i].checked = true;\n" +

" } else {\n" +

" frm.elements[i].checked = false;\n" +

" }\n" +

" // work here with the item templates multiple checkboxes\n" +

" } else if (idval.indexof(deletethis) != -1) {\n" +

" // check if any of the checkboxes are not checked, and then uncheck top select all checkbox\n" +

" if(frm.elements[i].checked == false) {\n" +

" frm.elements[1].checked = false; // check if any of the checkboxes are not checked, and then uncheck top select all checkbox\n" +

" }\n" +

" }\n" +

" }\n" +

"}" +

"//–> \n" +

"</script>";

//allows our .net page to add client-side script blocks when page loads, instead of the conventional html js tags.

registerclientscriptblock ("clientscript", jsscript);

webcontrol button = (webcontrol) page.findcontrol ("confirm");

button.attributes.add ("onclick", "return confirmdelete (this.form);");

objconnect = new sqlconnection ("server=(local);database=pubs;uid=sa;pwd=;");

if (!ispostback) {

binddata();

}

}

public void deletestore (object sender, eventargs e) {

string dgids = "";

bool bxschkd = false;

foreach (datagriditem i in mydatagrid.items) {

checkbox deletechkbxitem = (checkbox) i.findcontrol ("deletethis");

if (deletechkbxitem.checked) {

bxschkd = true;

// concatenate datagrid item with comma for sql delete

dgids += ((label) i.findcontrol ("storeid")).text.tostring() + ",";

}

}

// set up sql delete statement, using lastindexof to remove tail comma from string.

string deletesql = "delete from stores where stor_id in (" + dgids.substring (0, dgids.lastindexof (",")) + ")";

if (bxschkd == true) { // execute sql query only if checkboxes are checked, otherwise error occurs with initial null string

try {

sqlhelper.executenonquery (objconnect, commandtype.text, deletesql);

outputmsg.innerhtml += "<font size=4><b>store information has been deleted.</b></font>";

outputmsg.style["color"] = "green";

} catch (sqlexception err) {

outputmsg.innerhtml += err.message.tostring(); //"<font size=4><b>an error occurred and the record could not be deleted</b></font>";

outputmsg.style["color"] = "red";

}

//refresh data

binddata();

}

}

public void binddata() {

string sqlquery = "select stor_id as id, stor_name as store, city, state, zip from stores";

mydatagrid.datasource = sqlhelper.executedataset(objconnect, commandtype.text, sqlquery);

mydatagrid.databind();

objconnect.close();

objconnect = null;

}

} //end class

}//end namespace

conclusion

well, thats it. pretty awesome, and there was sure a lot to grasp as this certainly was a fairly complex article; but look at what you can do with a datagrid now? theres nothing preventing you from adding paging to it although youll have to delete whatever you need per page before paging to the next, or you could also store all your selected values in view state or any of of state methods, then pull them from there at the end.

at any rate, .net clearly demonstrates that its framework and all included is simply the best once again. period!

until next time. happy .neting

赞(0)
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com 特别注意:本站所有转载文章言论不代表本站观点! 本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。未经允许不得转载:IDC资讯中心 » DataGrid常见解决方案(三)–在DataGrid中选择,确认,删除多行复选框列表-.NET教程,VB.Net语言
分享到: 更多 (0)