ASP.net offers a powerful way to render information from a database or XML file:databinding. However, sometimes you need to being 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 this you need to use and each row in the data source, so th At your need a little finer control over how the ' data is ' bound to ' control. In this cases, you'll typically need to handle the Onitemdatabound event, which are fired for each item as it is bound t O your control. This gives for a LOT of flexibility, but unfortunately the code is a little bit hairy. Hopefully, who has an example would help! The ' all ', let me explain the this-example is taken to LIVE application:my Regular Expression Library over in my asp.net training website, aspsmith.com. You can clicking the IT in action by the here. You ll-what it is doing in a moment.
For my Regular Expression Library, I had several things I needed to adjust beyond the default databinding this my DataGrid Provided "Out-of-the-box". Firstly, I had a user_id field in me data that I wanted to convert to a user ' s email. Next, I wanted to limit how much of the Description field is displayed on the search results page, to avoid causing the P Age to get excessively long (since the Description field was a TEXT field in my database, and could therefore being many megab Ytes long). Lastly, I had an Edit link this allowed the owner of the regular expression to Edit it but I didn ' t want Le except if the current user is the owner of the expression. Let's have a "how to" this is done. The take a look at the rather lengthy Datagrid declaration. The important part is listed in red.
This event, Onitemdatabound, are supported by the any control of that supports data binding. 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 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 ());
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 your something big and ugly this actually sits on a production site. But don ' t fear, it'll all is clear to your in a moment, if it isn ' t already (even if your only know VB). Let ' s break this down.
The "6 lines declare our" and throw in some comments. As I said, I basically have three things I want to todo here:
Convert userid to an email link
Truncate the Description field
Hide the Edit link if current user isn't the owner
The only thing your really need to watch this is-to-make sure so your second ' s type is parameter-for-control You are using. This is pretty self-explanatory, but if you can ' t figure it out, can always look at the definition of the particular C Ontrol you are using in the Class Browser. For your vb.net users, just convert "//" to a single quote, get rid of the the {and switch the parameters to the type is Follo Wing 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 to every item in the bound control, including Items, Alternatingitems, separators, Headers, Fo Oters, etc. (complete list), we need to specify which kinds of items we are concerned with. In this case, we just want to deal and the main section of the control, so we check to make sure the item in question is Either an Item or a 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 your VB guys, | | means "Or".
Note:i neglected to use alternating items when I-wrote this application, so the user ' s email is displayed for ever Y other item, but the user ' s ID is displayed for the others!
Ok, now I ' ve got some tracing into place to help me with debugging. This just outputs the "current item", and lets me verify that it was in fact either a 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 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 are 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 is allows us to then reference the "user_id" element "the", using C # ' s array/collection Syntax (in VB this would use () instead of []), and convert the contents to a String, because it is what int32.parse ex Pects. Finally moving out to the black and Int32.Parse converts a String into an int. The results of this conversion are then stored to 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 the code uses some custom controls I wrote to handle my Users. The control are modelled after the ones found in the IBuySpy application. In this case, I Userdetails class so holds my user's name and email address by calling the Getuserdetails method of I U Ser 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 do. The red code is used to convert the orange code into a HyperLink. The orange code is used to find the control whose ID was "myuser" within the current item. In my template for my column in the My DataGrid, I have a <asp:hyperlink id= "myuser"/> tag that this code refers to. The rest of this blocks 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 being old hat. The next line pretty more does the same stuff as the previous line, but in this case we ' re setting the NavigateUrl Propert Y of our HyperLink to "mailto:" and the user's email address. Once again this are 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. The ' description ' from the ' current DataItem ' converting it to a DbDataRecord type grab. Then we convert it to a string and assign it to a variable, desc. Next, we check to the "if its" is than, and if it are, we convert it to just the left characters (using S Ubstring-in VB, we would have used left ()) and tack on a "..." to the ' end ' to show the users of that there are more text. Finally, we use the FindControl syntax once of the description Label control within we template, and set its The 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 data Bound list. In this case, I use the ' I 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 Pro Perty to False. In order to does this, I had to make my table cell a htmlcontrol by adding runat= the "server" to it and giving it 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 I to hide something if it value is null. Just do the same thing I ' m doing here, but replace the IF statement this is referring to security with one that checks the Value of the variable. You'll probably need to use the (System.Data.Common.DbDataRecord) e.item.dataitem) syntax described to access R data and check it for NULL, but that's all there are 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 which is the best thing so can be said to any example. You can be aspsmith the IT in action at the Regular Expression Library. If you have trouble getting the this to work with your own, I suggest that for you, the code with compare, and if that D OESN ' t yield any insight, ask the asp.net data experts on the Aspng data Listserv. Be sure to include your failing code in your ques
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.