首页 > 编程 > ASP > 正文

Hiding/Manipulating Databound Items(转载www.aspallia

2024-05-04 11:06:28
字体:
来源:转载
供稿:网友

asp.net offers a powerful way to render information from a database or xml file: databinding. however, sometimes you need to be able to perform the databinding for almost all of the items in the data source. or perhaps you have some special formatting or secondary data that you need to use with each row in the data source, so that you need a little finer control over how the data is bound to the control. in these cases, you will typically need to handle the onitemdatabound event, which is fired for each item as it is bound to your control. this gives you a lot of flexibility, but unfortunately the code is a little bit hairy. hopefully, having an example will help! first of all, let me explain that this example is taken from a live application: my regular expression library over at my asp.net training website, aspsmith.com. you can see it in action by clicking here. you'll see what it is doing in a moment.

for my regular expression library, i had several things i needed to adjust beyond the default databinding that my datagrid provided "out-of-the-box". firstly, i had a user_id field in my data that i wanted to convert to a link to a user's email. next, i wanted to limit how much of the description field was displayed on the search results page, to avoid causing the page to get excessively long (since the description field is a text field in my database, and could therefore be many megabytes long). lastly, i had an edit link that allowed the owner of the regular expression to edit it, but i didn't want that to be visible except if the current user was the owner of the expression. let's see how this was done. first, let's take a look at my (rather lengthy) datagrid declaration. the important part is listed in red.

default.aspx excerpt <asp:datagrid id="dgregexp" runat="server" autogeneratecolumns="false" bordercolor="black" borderwidth="1" style="margin-left:20px;" pagesize="5" allowpaging="true" allowcustompaging="true" onpageindexchanged="dgregexp_pageindexchanged" onitemdatabound="dgregexp_itemdatabound" gridlines="horizontal" pagerstyle-mode="numericpages" pagerstyle-horizontalalign="center" pagerstyle-position="topandbottom" pagerstyle-width="100%" headerstyle-backcolor="#cc0000" headerstyle-font-bold="true" headerstyle-font-name="verdana" headerstyle-font-size="9pt" headerstyle-forecolor="white" itemstyle-font-name="arial" itemstyle-font-size="8pt" alternatingitemstyle-backcolor="#dddddd">  

this event, onitemdatabound, is supported by any control that supports data binding. you can use it with datagrids, datalists, repeaters, etc. in this case, i have mapped mine to the "dgregexp_itemdatabound" event handler, which we'll take a look at now:

default.aspx excerpt protected void dgregexp_itemdatabound(object sender, datagriditemeventargs e)
{
// for items and alternatingitems,
// convert userid to email link
// truncate description
// hide edit link if not owner
if(e.item.itemtype == listitemtype.item || e.item.itemtype == listitemtype.alternatingitem)
{
trace.write("itemdatabound",e.item.dataitem.gettype().tostring());

int user_id = int32.parse(((system.data.common.dbdatarecord)e.item.dataitem)["user_id"].tostring());
trace.write("itemdatabound", "user_id: " + user_id.tostring());

aspalliance.dal.userdetails objuser = aspalliance.dal.user.getuserdetails(user_id);
((system.web.ui.webcontrols.hyperlink)e.item.findcontrol("myuser")).text =
objuser.first_name + " " + objuser.last_name + " (" + objuser.email + ")";
((system.web.ui.webcontrols.hyperlink)e.item.findcontrol("myuser")).navigateurl = "mailto:" + objuser.email;
trace.write("itemdatabound", "myuser.text: " + ((system.web.ui.webcontrols.hyperlink)e.item.findcontrol("myuser")).text);

string desc = ((system.data.common.dbdatarecord)e.item.dataitem)["description"].tostring();
if(desc.length > 100)
{desc = desc.substring(0,99);
desc += "...";
}
((system.web.ui.webcontrols.label)e.item.findcontrol("description")).text = desc;
aspalliance.dal.security sec = new aspalliance.dal.security(this.request);
if((sec.user_id == 0) || (sec.user_id != user_id) || (!sec.isauthenticated))
{
((system.web.ui.htmlcontrols.htmltablecell)e.item.findcontrol("edittd")).visible = false;
}}}}


ok, now that's what i call an example! none of that wussy little "just for demonstration" three lines of code stuff for us. no, we're going to go all out and show you something big and ugly that actually sits on a production site. but don't fear, it will all be clear to you in a moment, if it isn't already (even if you only know vb). let's break this down.

the first 6 lines declare our method and throw in some comments. as i said, i basically have three things i want to do here:

convert userid to an email link
truncate the description field
hide the edit link if current user is not the owner
the only thing you really need to watch here is to make sure that your second parameter's type is correct for the control you are using. this is pretty self-explanatory, but if you can't figure it out, you can always look at the definition of the particular control you are using in the class browser. for you vb.net users, just convert "//" to a single quote, get rid of the { and switch the parameters to the type is following the name and has "as" in front of it.

next, we need to make sure we're dealing with the correct item type. since this event is raised for every item in the bound control, including items, alternatingitems, separators, headers, footers, etc. ( complete list), we need to specify which kinds of items we are concerned with. in this case, we just want to deal with the main section of the control, so we check to make sure the item in question is either an item or an alternatingitem. this is handled by the if statement. we get the current item from our input parameter, e, and compare it to the itemtypes we are concerned with. for you vb guys, || means "or".

note: i neglected to use alternating items when i first wrote this application, so the user's email was displayed for every other item, but the user's id was displayed for the others!

ok, now i've got some tracing in place to help me with debugging. this just outputs the type of the current item, and lets me verify that it is in fact either an item or an alternatingitem. you can leave this out of your implementation.

next i grab the user_id. this is one ugly piece of code. let me repeat it here and go through it piece by piece:
int user_id = int32.parse( ((system.data.common.dbdatarecord)e.item.dataitem)["user_id"].tostring()); let's start with the innermost parentheses, in red. this is c#'s method of type casting, and is necessary to convert the current dataitem to the dbdatarecord type. the orange set of parentheses completes this operation. for all intents and purposes, the contents of the orange parentheses are considered to be a dbdatarecord. moving on to the green, this allows us to then reference the "user_id" element of this record, using c#'s array/collection syntax (in vb this would use () instead of []), and convert the contents to a string, because that is what int32.parse expects. finally moving out to the black, int32.parse converts a string into an int. the results of this conversion are then stored in my user_id variable of type int. on the next line i have some more diagnostic code to output the user_id to the trace log.

ok, so now we have a user_id. the next chunk of code uses some custom controls that i wrote to handle my users. the control is modelled after the ones found in the ibuyspy application. in this case, i userdetails class that holds my user's name and email address by calling the getuserdetails method of my user class. the next line is another hairy one, though:
( (system.web.ui.webcontrols.hyperlink)e.item.findcontrol("myuser")).text = objuser.first_name + " " + objuser.last_name + " (" + objuser.email + ")";
again, starting from the middle most parens, we have another typecasting operation being done. the red code is used to convert the orange code into a hyperlink. the orange code is used to find the control whose id is "myuser" within the current item. in my template for my column in my datagrid, i have an <asp:hyperlink id="myuser"/> tag that this code refers to. the rest of this block of code sets the text of this hyperlink to the user's name and email address. the hyperlink tag looks like this in my datagrid: <asp:hyperlink id="myuser" runat="server"> <%# databinder.eval(container.dataitem, "user_id") %> </asp:hyperlink>  


by now this typecasting is getting to be old hat. the next line pretty much does the same stuff as the previous line, but in this case we're setting the navigateurl property of our hyperlink to "mailto:" and the user's email address. once again this is followed by some more diagnostic tracing.
((system.web.ui.webcontrols.hyperlink)e.item.findcontrol("myuser")).navigateurl = "mailto:" + objuser.email;

that's it for the email. task 1 is complete. now we want to truncate the description if it is too long. we do this using similar techniques. first, we grab the "description" from the current dataitem after converting it to a dbdatarecord type. then we convert it to a string and assign it to a variable, desc (all in one line). next, we check to see if its length is more than 100, and if it is, we convert it to just the left 100 characters (using substring -- in vb we would have used left()) and tack on a "..." to the end to show the users that there is more text. finally, we use the findcontrol syntax once more to locate the description label control within our template, and set its text property to the result.

that's 2 tasks down. one to go. this is the most commonly asked for feature of datagrids and datalists: how to hide a particular row or item within a databound list. in this case, i use my custom security control to determine if the user is the owner of the current regular expression. if they aren't, or if they aren't logged in and authenticated, then i set the table cell holding my edit tag's visible property to false. in order to do this, i had to make my table cell an htmlcontrol by adding runat="server" to it and giving it an id. i named the table cell "edittd", and i can use findcontrol to locate the cell within my item and access its properties. the cell itself is listed here: <td align="right" valign="top" id="edittd" runat="server">
[<a href='edit.aspx?regexp_id=<%# server.urlencode(databinder.eval(container.dataitem, "regexp_id").tostring()) %>'
title="click to edit.">edit</a>]
</td>  
that's all there is too it. for most people, they want to know how to hide something if its value is null. just do the same thing i'm doing here, but replace the if statement that is referring to security with one that checks the value of the variable. you will probably need to use the (system.data.common.dbdatarecord)e.item.dataitem) syntax described earlier to access your data and check it for null, but that's all there is to it.

summary
manipulating or hiding individual elements of a databound list or grid is not very difficult once you know a few tricks. however, the code is pretty darned ugly. the code on this page works, and that is the best thing that can be said of any example. you can see it in action at aspsmith regular expression library. if you have trouble getting this to work with your own, i suggest that you first compare you code with mine, and if that doesn't yield any insight, ask the asp.net data experts on the aspng data listserv. be sure to include your failing code in your question.
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表