Home>

In the previous sections, we explained how to upload and display binary image data in asp.net.In this section, we will introduce how to edit and delete existing binary data in gridview.

preface:

In the previous 3 chapters we added a lot of functions for processing binary data.We first added the brochurepath column to the categories and updated the architecture.Similarly, in order to process the existing picture column in the table categorie, we have added corresponding methods in the data access layer and business logic layer.At the same time we create a page,Display binary data in the gridview control-contains a download link to the instruction booklet,And the pictures of each class are displayed in theelement. At the same time we add a detailsview control for users to add new classes,And upload its pictures and brochure data.

The rest is to add editing and deleting functions,In this chapter, we will implement the built-in editing and deleting functions of the gridview control.When editing a class,We allow users to replace the original with any specified picture;You can also replace the existing ones with new brochures,Booklet files are no longer even included.let's start!

Step 1:Update the data access layer

Although the data access layer contains automatically generated insert, update, and delete methods, they are all based on the main query of the categoriestableadapter,So it doesn't include the picture column. Naturally, the insert and update methods do not include corresponding parameters in the picture column.Just like what was done in Chapter 56,We need to create a new tableadapter method to update the categories table.

Right-click the top of the categoriestableadapter and select "Add Query" to open the tableadapter query setting wizard,We first select "Use sql statement", click next, then select "update", and then click next.

Figure 1:Selecting the "update" option

We now need to specify the update sql statement. The wizard automatically creates an update statement based on the tableadapter main query (it updates the categoryname, description and brochurepath values). Update the statement to include the picture column, and the @picture parameter, as follows:

update [categories] set
 [categoryname][email protected], [description][email protected], [brochurepath][email protected], [picture][email protected]
where (([categoryid][email protected]_categoryid))

Finally, the wizard asked us to name the new tableadapter method,Let's take updatewithpicture and click finish.

Figure 2:Name the new method updatewithpicture

Step 2:Add a new business logic method

In addition to updating dal, we need to update bll to include methods for updating and deleting classes.Here are the methods that the presentation layer needs to call:

To delete a class,We use the automatically generated delete method of the categoriestableadapter, and add the following method to the categoriesbll:

[system.componentmodel.dataobjectmethodattribute
 (system.componentmodel.dataobjectmethodtype.delete, true)]
public bool deletecategory (int categoryid)
{
 int rowsaffected=adapter.delete (categoryid);
 //return true if precisely one row was deleted, otherwise false
 return rowsaffected == 1;
}
</p>
<p>
</pre>
<p>
This tutorial, in order to update a class,We will create 2 methods. A method takes a picture value and calls the updatewithpicture method we just added to the categoriestableadapter. The other method only accepts the categoryname, description, and brochurepath values, and calls the automatically generated update statement in the categoriestableadapter class. Why use 2 methods?In some cases,When the user updates the class, its picture is also updated,Then you need to upload a new picture.
The data of the uploaded image will be used in the update statement;
another situation,The user only wants to update the name and description of the class, so we need to use 2 update methods.
The business logic layer will determine which method to use based on whether a picture value is passed in.
</p>
</div>
<p>
To that end,We are going to add 2 methods to the categoriesbll class. The names are updatecategory. The first method accepts three strings, a byte array and an int. The second method accepts three strings and 1 An int. The three string parameters represent the name, description, and brochure file path of the class.
The byte array contains the picture data of the class, and int represents the categoryid of the class record. We noticed that
When the byte array passed in is null, the first method will call the second method.
</p>
<div>
<pre>
[system.componentmodel.dataobjectmethodattribute
 (system.componentmodel.dataobjectmethodtype.update, false)]
public bool updatecategory (string categoryname, string description, string brochurepath, byte [] picture, int categoryid)
{
 //if no picture is specified, use other overload
 if (picture == null)
 return updatecategory (categoryname, description, brochurepath, categoryid);
 //update picture, as well
 int rowsaffected=adapter.updatewithpicture
 (categoryname, description, brochurepath, picture, categoryid);
 //return true if precisely one row was updated, otherwise false
 return rowsaffected == 1;
}
[system.componentmodel.dataobjectmethodattribute
 (system.componentmodel.dataobjectmethodtype.update, true)]
public bool updatecategory (string categoryname, string description, string brochurepath, int categoryid)
{
 int rowsaffected=adapter.update
 (categoryname, description, brochurepath, categoryid);
 //return true if precisely one row was updated, otherwise false
 return rowsaffected == 1;
}

Step 3:Copy function

In the last chapter,We created an uploadindetailsview.aspx page, listing all classes in a gridview control,Add a new class via a detailsview control.In this tutorial,We will extend the gridview control to support editing and deleting functions.But we no longer use the uploadindetailsview.aspx page, let's create a new page in the ~/binarydata folder,updatinganddeleting.aspx, copy and paste the declaration code of the uploadindetailsview.aspx page to the updatinganddeleting.aspx page.

Open the uploadindetailsview.aspx page and copy the declaration code in theelement,Just like Figure 3. Next, open the updatinganddeleting.aspx page and paste the code into theelement. Similarly, copy the background code of the uploadindetailsview.aspx page to updatinganddeleting.aspx.

Figure 3:Copy the declaration code of the uploadindetailsview.aspx page

When you are done, log in to updatinganddeleting.aspx and you will see the same output.It feels like using the uploadindetailsview.aspx page.

Step 4:Add delete function of objectdatasource and gridview

Just like in tutorial 16 "Overview of inserting, updating, and deleting dataThe same thing is discussed in "As long as the data source bound to the gridview control supports the "delete" function, we can enable the delete function for the gridview control.However, the objectdatasource (that is, categoriesdatasource) bound to the gridview control currently does not support deletion.

To support deletion,In the smart tag of objectdatasource, click "Configure Data Source" until you reach the "Define Data Method" interface. Although only the insertdata attribute and selectmethod attribute of the objectdatasource control are currently specified, the wizard automatically specifies the updatecategory method and the deletecategory method for the update tag and the delete tag, respectively. why?Because we use the dataobjectmethodattribute attribute in the categoriesbll class for the above two methods, the purpose is to make it the default "update" and "delete" methods, respectively.

But now we select "(none)" in the drop-down list of the update tag, and the delete tag still has the deletecategory method. We will add the update function in step 6.

Figure 4:Setting the objectdatasource control to use the deletecategory method

Note:After setting up,visual studio will ask you if you "refresh the columns and primary keys", choose no, because choosing yes will overwrite any columns we have customized.

Now, the objectdatasource control will contain the deletemethod attribute and the corresponding deleteparameter parameter. We remember mentioning in previous tutorials,When using the wizard to specify the method,Visual Studio will automatically set the oldvaluesparameterformatstring property of the objectdatasource control to original_ {0}, which will cause problems when updating and deleting.To do this, either the property will be cleared,Either set it to the default {0} value. For a more detailed discussion of this property, see Tutorial 16Overview of inserting, updating, and deleting data》

When you're done, the declaration code for the objectdatasource control should look like this:

<asp:objectdatasource runat="server"
 oldvaluesparameterformatstring="{0}" selectmethod="getcategories"
 typename="categoriesbll" insertmethod="insertwithpicture"
 deletemethod="deletecategory">
 <insertparameters>
 <asp:parameter name="categoryname" type="string" />
 <asp:parameter name="description" type="string" />
 <asp:parameter name="brochurepath" type="string" />
 <asp:parameter name="picture" type="object" />
 </insertparameters>
 <deleteparameters>
 <asp:parameter name="categoryid" type="int32" />
 </deleteparameters>
</asp:objectdatasource>

After setting up the objectdatasource, you can enable the delete function of the gridview,To do this, click on "Delete Options" in its smart tab. This will add a commandfield to the gridview with the showdeletebutton property of true.

Figure 5:Enable the delete function of the gridview control

Take a few minutes to test the delete function.Since there is a foreign key categoryid between the tables products and the categories, when you delete any of the 8 existing classes,You will get a foreign key constraint conflict exception.For smooth implementation testing,We need to add a new class with pictures and description booklets,As shown in Figure 6, the booklet is test.pdf, and Figure 7 is the gridview control interface with the test class added.

Figure 6:Add a test class with brochure and image files

Figure 7:After adding the test class,Show in gridview control

Refresh the Solution Explorer in visual studio,You will see the test.pdf file in the folder ~/brochures (see Figure 8)

Next, click the delete link of the test class.Causes the deletecategory method of categoriesbll, which in turn calls the delete method of the dal layer and sends the appropriate delete command to the database. Finally, the data is re-bound to the gridview control, and the test class is no longer displayed.

Although the test class has been successfully deleted from the categories table, the corresponding booklet stored in the file system still exists.Refresh solve explorer,You will find test.pdf still in the ~/brochures folder.

Figure 8:The test.pdf file is not deleted from the file system

Step 5:Delete the residual brochure file

problem A problem when binary data is not stored in the database is:when deleting a database record,We need to take another step to delete the binary data file corresponding to this record.When the delete command is executed, some pre- and post-action events will occur, and we need to create corresponding event handlers.Before the records in the categories table are deleted,We need to determine the path of the corresponding pdf file,However, we will not delete the corresponding pdf file before deleting the record, in case an exception occurs or the record is not deleted.

From the chronological order of events,The rowdeleting event of the gridview control occurs before the delete command of the objectdatasource control is called;The rowdeleted event occurs after the delete command of the objectdatasource control is called.Create these 2 event handlers,code show as below:

//a page variable to "remember" the deleted category "s brochurepath value
string deletedcategoryspdfpath=null;
protected void categories_rowdeleting (object sender, gridviewdeleteeventargs e)
{
 //determine the pdf path for the category being deleted ...
 int categoryid=convert.toint32 (e.keys ["categoryid"]);
 categoriesbll categoryapi=new categoriesbll ();
 northwind.categoriesdatatable categories =
 categoryapi.getcategorybycategoryid (categoryid);
 northwind.categoriesrow category=categories [0];
 if (category.isbrochurepathnull ())
 deletedcategoryspdfpath=null;
 else
 deletedcategoryspdfpath=category.brochurepath;
}
protected void categories_rowdeleted (object sender, gridviewdeletedeventargs e)
{
 //delete the brochure file if there were no problems deleting the record
 if (e.exception == null)
 {
 //is there a file to delete?
 if (deletedcategoryspdfpath!=null)
 {
  system.io.file.delete (server.mappath (deletedcategoryspdfpath));
 }
 }
}

RowIn the rowdeleting event handler,Get the categoryid value of the deleted record from the datakeys collection of the gridview control, and here,We access the datakeys collection via e.keys. Then, call the getcategorybycategoryid (categoryid) method of the category categoriesbll to return the information of the deleted record.If the returned return path value is not null, it is assigned to the page parameter deletedcategoryspdfpath, and then the file is deleted in the rowdeleted event handler.

Note:In the rowdeleting event handler,Instead of returning the path information of the deleted record, we added the path to the datakeynames property of the gridview, and then accessed the value of the record by accessing e.keys.Although this slightly increases the view state of the gridview,But reduced the necessary code,It also saves a step to access the database.

After calling the delete command of the objectdatasource control, the rowdeleted event of the gridview control occurs immediately. If there is no exception in the deletion process and the deletedcategoryspdfpath value is not empty,Then delete the corresponding pdf file from the file system.We have noticed,The code does not delete the class picture, that is because the picture data is directly stored in the database,It is deleted when the record is deleted.

After adding the above two event handlers,Test the deletion again.When deleting a class,Its corresponding pdf file has also been deleted.

Let ’s take a deeper look at adding update functions to deal with class brochures and pictures. Step 6 explores techniques for updating brochure information.Chapter 7 discusses updating pictures.

Step 6:Update the brochure of the class

Just like in tutorial 16 "Overview of inserting, updating, and deleting dataThe same thing is discussed in "If the gridview data source control supports editing,Then we can enable the editing function of the gridview control.Currently, the objectdatasource control named categoriesdatasource does not support editing.Let's add it.

Click on the "set data source" link of the objectdatasource control, all the way to the "define the data method" interface. Because the overloaded updatecategory method in categoriesbll uses the dataobjectmethodattribute attribute, the drop-down list of the update tag automatically selects this method.It contains 4 input parameters (not including picture). We choose another overloaded updatecategory method with 5 input parameters.

Figure 9:Set the objectdatasource control to use the updatecategory method with the picture parameter

The objectdatasource control now contains the updatemethod attribute and the corresponding updateparameters parameter set. As mentioned in step 4,When using the setup wizard,Visual Studio will set the oldvaluesparameterformatstring property of the objectdatasource control to original_ {0}, which causes problems when calling the update and delete methods.So either clear the property,Either set the attribute to {0}.

When you're done, the declaration code for the objectdatasource control should look similar to the following:

<asp:objectdatasource runat="server"
 oldvaluesparameterformatstring="{0}" selectmethod="getcategories"
 typename="categoriesbll" insertmethod="insertwithpicture"
 deletemethod="deletecategory" updatemethod="updatecategory">
 <insertparameters>
 <asp:parameter name="categoryname" type="string" />
 <asp:parameter name="description" type="string" />
 <asp:parameter name="brochurepath" type="string" />
 <asp:parameter name="picture" type="object" />
 </insertparameters>
 <deleteparameters>
 <asp:parameter name="categoryid" type="int32" />
 </deleteparameters>
 <updateparameters>
 <asp:parameter name="categoryname" type="string" />
 <asp:parameter name="description" type="string" />
 <asp:parameter name="brochurepath" type="string" />
 <asp:parameter name="picture" type="object" />
 <asp:parameter name="categoryid" type="int32" />
 </updateparameters>
</asp:objectdatasource>

To enable editing,Select "Edit" from the smart tag of the gridview control. This will set the showeditbutton property of the commandfield to true, and the result is an edit button for each rowWill be rendered as update and cancel buttons)

Figure 10:Enabling the editing function of the gridview control

View View this page from your browser,Click the edit button for a record. The categoryname and description columns are rendered as a text box.Since the brochurepath templatefield doesn't have an edititemtemplate template, it still renders its itemtemplate template-a link to the brochure. The picture column is rendered as a text box,And the text attribute of the picture imagefield is assigned as the dataimageurlfield value, here, the categoryid.

Figure 11:Brochurepath column has no editing interface

Custom brochurepath editing interface

We can create an editing interface for brochurepath templatefield,We can choose:

Leave it as is

. Upload new brochure for update

Delete the brochure (so thatClass has no corresponding brochure)

We should also update the editing interface of picture imagefield,However, we will discuss it in step 7.

select Select "edit template" in the smart tag of the gridview control, and then select the edititemtemplate template of the broochpath templatefield from the drop-down list. Add a radiobuttonlist web control in the template, whose id is brochureoptions;the autopostback property is true. Then click the oval area of ​​the items property in the properties window.Enter the listitem collection editor interface and add options with values ​​of 1, 2, and 3 respectively:

.use current brochure

.remove current brochure

.upload new brochure

Set the selected property of the first listitem to true.

Figure 12:Add 3 listitems to the radiobuttonlist control

Under the radiobuttonlist control,Add a fileupload control with id brochureupload and set its visible property to false.

Figure 13:Add radiobuttonlist and fileupload controls to the edititemtemplate template

The radiobuttonlist control provides the user with three choices. The fileupload control will only be displayed when "upload new brochure" is selected.To do this, we create an event handler for the selectedindexchanged event of the radiobuttonlist control,as follows:

protected void brochureoptions_selectedindexchanged (object sender, eventargs e)
{
 //get a reference to the radiobuttonlist and its parent
 radiobuttonlist brochureoptions=(radiobuttonlist) sender;
 control parent=brochureoptions.parent;
 //now use findcontrol ("controlid") to get a reference of the
 //fileupload control
 fileupload brochureupload =
 (fileupload) parent.findcontrol ("brochureupload");
 //only show brochureupload if selectedvalue="3"
 brochureupload.visible=(brochureoptions.selectedvalue == "3");
}

Because the radiobuttonlist control and fileupload control appear in the same template at the same time,We need to programmatically access these two controls. In the selectedindexchanged event handler,We refer to the radiobuttonlist control by entering the sender parameter. In order to get the fileupload control, we need to use the parent control of the radiobuttonlist and use the findcontrol ("controlid") method. Once we have obtained both the radiobuttonlist and fileupload controls, as long as the selectedvalue of the radiobuttonlist control is equal to 3, that is, the value of the "upload new brochure" listitem, set the visible property of the fileupload control to true.

After adding the above code,Take a few minutes to test the edit page.Click the edit button of a row, the "use current brochure" item is selected by default, and another item is selected.The page generates a postback.If item 3 is selected, the fileupload control will be displayed.Otherwise it is in stealth.Figure 14 shows how the edit button is clicked.Figure 15 shows the situation when "upload new brochure" is selected.

Figure 14:"use current brochure" option selected by default

Figure 15:The fileupload control is displayed when "upload new brochure" is selected

Save the brochure file and update the brochurepath column

When the update button of the gridview control is clicked, the rowupdating event is triggered, the update command of the objectdatasource control is called, and then the rowupdated event of the gridview control is triggered. Similar to the deleting process,We need to create handlers for these events.In the rowupdating event handler,We need to determine what to do next based on the selectedvalue of radiobuttonlist.

If the selectedvalue is 1, we will leave the rochurepath unchanged. Therefore, we set the brochurepath parameter of the objectdatasource control to the brochurepath value of the record that is currently being edited, with the method e.newvalues ​​["brochurepath"]=value.

If the selectedvalue value is 2, it means that the brochurepath is set to null. To do this, we need to set the brochurepath parameter of the objectdatasource control to nothing, and the result is to use null in the update command. If a corresponding brochure file exists, we must delete it,The premise is that no exception is thrown.

If the selectedvalue is 3, we must ensure that the user has uploaded a pdf file and saved it in the file system,Then update the recorded routepath value. We need to delete the previous file that was replaced,Of course, the premise is that no exception is raised.

In the previous chapter,When adding a new record in the detailsview control,Triggers the itemserting event of the detailsview control. In this chapter, when the selected value of the radiobuttonlist control is 3 (that is, when we select upload new brochure), the next steps to take are actually similar to the functions implemented by the itemserting event handler of the detailsview control.Depending on the function implemented,I divided it into 2 methods:

.processbrochureupload (fileupload, out bool):It takes a fileupload control instance as an input parameter,The result is a boolean. Determine whether to continue the update or delete operation based on the Boolean value.Or cancel the operation.This method returns its path if there is an upload file,Otherwise it returns null.

.deleterememberedbrochurepath:If the page variable deletedcategoryspdfpath is not null, delete the file specified by this parameter.

The following is the code of the above 2 methods.Note that the processbrochureupload method and the itemserting event handler of the detailsview control have some similarities.In this chapter, we update the event handler of the detailsview control to use these new methods.Download the code for this chapter,Check out our modifications to the event handler of the detailsview control.

private string processbrochureupload
 (fileupload brochureupload, out bool canceloperation)
{
 canceloperation=false;//by default, do not cancel operation
 if (brochureupload.hasfile)
 {
 //make sure that a pdf has been uploaded
 if (string.compare (system.io.path.getextension (brochureupload.filename),  ".pdf", true)!=0)
 {
  uploadwarning.text =
  "only pdf documents may be used for a category" s brochure. ";
  uploadwarning.visible=true;
  canceloperation=true;
  return null;
 }
 const string brochuredirectory="~/brochures /";
 string brochurepath=brochuredirectory + brochureupload.filename;
 string filenamewithoutextension =
  system.io.path.getfilenamewithoutextension (brochureupload.filename);
 int iteration=1;
 while (system.io.file.exists (server.mappath (brochurepath)))
 {
  brochurepath=string.concat (brochuredirectory, filenamewithoutextension,  "-", iteration, ".pdf");
  iteration ++;
 }
 //save the file to disk and set the value of the brochurepath parameter
 brochureupload.saveas (server.mappath (brochurepath));
 return brochurepath;
 }
 else
 {
 //no file uploaded
 return null;
 }
}
private void deleterememberedbrochurepath ()
{
 //is there a file to delete?
 if (deletedcategoryspdfpath!=null)
 {
 system.io.file.delete (server.mappath (deletedcategoryspdfpath));
 }
}

Use the above two methods in the rowupdating and rowupdated event handlers of the gridview control, as follows:

protected void categories_rowupdating (object sender, gridviewupdateeventargs e)
{
 //reference the radiobuttonlist
 radiobuttonlist brochureoptions =
 (radiobuttonlist) categories.rows [e.rowindex] .findcontrol ("brochureoptions");
 //get brochurepath information about the record being updated
 int categoryid=convert.toint32 (e.keys ["categoryid"]);
 categoriesbll categoryapi=new categoriesbll ();
 northwind.categoriesdatatable categories =
 categoryapi.getcategorybycategoryid (categoryid);
 northwind.categoriesrow category=categories [0];
 if (brochureoptions.selectedvalue == "1")
 {
 //use current value for brochurepath
 if (category.isbrochurepathnull ())
  e.newvalues ​​["brochurepath"]=null;
 else
  e.newvalues ​​["brochurepath"]=category.brochurepath;
 }
 else if (brochureoptions.selectedvalue == "2")
 {
 //remove the current brochure (set it to null in the database)
 e.newvalues ​​["brochurepath"]=null;
 }
 else if (brochureoptions.selectedvalue == "3")
 {
 //reference the brochurepath fileupload control
 fileupload brochureupload =
  (fileupload) categories.rows [e.rowindex] .findcontrol ("brochureupload");
 //process the brochureupload
 bool canceloperation=false;
 e.newvalues ​​["brochurepath"] =
  processbrochureupload (brochureupload, out canceloperation);
 e.cancel=canceloperation;
 }
 else
 {
 //unknown value!
 throw new applicationexception (
  string.format ("invalid brochureoptions value, {0}",  brochureoptions.selectedvalue));
 }
 if (brochureoptions.selectedvalue == "2" ||
 brochureoptions.selectedvalue == "3")
 {
 //"remember" that we need to delete the old pdf file
 if (category.isbrochurepathnull ())
  deletedcategoryspdfpath=null;
 else
  deletedcategoryspdfpath=category.brochurepath;
 }
}
protected void categories_rowupdated (object sender, gridviewupdatedeventargs e)
{
 //if there were no problems and we updated the pdf file, //then delete the existing one
 if (e.exception == null)
 {
 deleterememberedbrochurepath ();
 }
}

Note:How the rowupdating event handler uses a series of conditional statements to achieve the corresponding function according to the selectedvalue value.

Using the above code,We can edit a class,Use its current brochure, or do not use the brochure, or use a new brochure. Set breakpoints in the rowupdating and rowupdated event handlers to better understand the processing flow.

Step 7:Upload new picture

The editing interface of picture imagefield is rendered as a text box,It shows the value of the dataimageurlfield property.During the editing process,The gridview control passes a parameter to the objectdatasource,The parameter is the dataimageurlfield attribute of imagefield;the parameter value is the value in the input text box of the editing interface.When pictures are stored in the file system,When the dataimageurlfield attribute contains the full url to access the image, it is appropriate to do so.under these circumstances,In the editing interface,The text box will display the url of the image. no doubt,The default interface does not allow users to upload new pictures,But the user can modify the url value of the picture. However, this will not happen in this tutorial,Because picture data is stored directly in the database,And the dataimageurlfield attribute is set to the categoryid value.

In order to better understand what will happen when editing the imagefield of a line in this tutorial,We make the following assumptions:the user edits a categoryid value of 10 lines, and the picture imagefield is rendered as a text box,Display 10, assuming the user changes it to 50 and clicks the update button, the page returns,The gridview control initially generates a parameter named categoryid with a value of 50. Add values ​​to the datakeys set before gridview passes this parameter (along with the parameter categoryname and parameter description).Therefore, the categoryid value of the current row is 10 and overwritten. In short, the editing interface of imagefield has no effect on the editing process of this tutorial,Because imagefield's dataimageurlfield attribute and datakey value are the same value.

When pictures are stored in the database,imagefield also makes it easy to display.But in the editing interface we don't need to use text boxes,A fileupload control is provided for use by end users when changing pictures.Unlike brochurepath, we don't allow class images to be empty-users either provide new images or use the current image.

Editing interface for custom imagefield,We need to convert it into a templatefield. In the smart tag of the gridview control, click "Edit Columns", select imagefield after entering, and then click the "convert this field into a templatefield" link.

Figure 16:Converting imagefield to templatefield

The converted templatefield consists of 2 templates.As the following declaration code shows,The itemtemplate template contains an image web control whose imageurl property is specified by a data binding syntax.The data binding syntax is based on imagefield's dataimageurlfield and dataimageurlformatstring properties. The edititemtemplate template contains a textbox whose text property is bound to the value of the dataimageurlfield property.

<asp:templatefield>
 <edititemtemplate>
 <asp:textbox runat="server"
  text="<%#eval (" categoryid ")%>"></asp:textbox>
 </edititemtemplate>
 <itemtemplate>
 <asp:image runat="server"
  imageurl="<%#eval (" categoryid ",  "displaycategorypicture.aspx?categoryid={0}")%>"/>
 </itemtemplate>
</asp:templatefield>

We need to update the edititemtemplate template to include a fileupload control. From the smart tag point of the gridview control, "Edit Template", then select the edititemtemplate template of picture templatefield from the drop-down list. In the template you will see a textbox, delete it.Drag a fileupload control from the toolbox to the page,Let its id be pictureupload. At the same time, add the following text to the template:"to change the category" s picture, specify a new picture. To keep the category "s picture the same, leave the field empty".

Figure 17:Adding a fileupload control to the edititemtemplate template

After customizing the editing interface,View in browser.In read-only mode,The class picture is no different than beforeWhen the edit button is clicked, the picture column will render a piece of text and a fileupload control.

Figure 18:The editing interface contains a fileupload control

Remember that we set the objectdatasource control to call the updatescategory method of categoriesbll. One input parameter of this method is an array.The data used to process the image.If the array is a null value, another overloaded updatecategory method is called. The update sql statement of the overloaded updatecategory method does not change the picture column, so the picture of the class is not changed by any.In the rowupdating event handler of the gridview control,We programmatically access the fileupload control named pictureupload to determine if a file has been uploaded.If no file is uploaded,We will not specify a value for the parameter picture;otherwise, if a file is uploaded,We will make sure it is a jpg file,And pass it to the objectdatasource control through the parameter picture.

Just like the code in step 6,Most of the code we will use at this time already exists in the itemserting event handler of the detailsview control.Now we create a new method validpictureupload and update the itemserting event handler to use that method.

Add to Add the following code at the beginning of the rowupdating event handler of the gridview control,This is important,Because we don't want to store an unqualified upload file in the file system.

//reference the pictureupload fileupload
fileupload pictureupload =
 (fileupload) categories.rows [e.rowindex] .findcontrol ("pictureupload");
if (pictureupload.hasfile)
{
 //make sure the picture upload is valid
 if (validpictureupload (pictureupload))
 {
 e.newvalues ​​["picture"]=pictureupload.filebytes;
 }
 else
 {
 //invalid file upload, cancel update and exit event handler
 e.cancel=true;
 return;
 }
}

Validpictureupload (fileupload) method has only one input parameter of fileupload control type,Check the extension of the uploaded file to ensure that the uploaded file is in jpg format. This method will only be called when a file is uploaded;If no file is uploaded,The parameter picture can only use its default value-null. If an image is uploaded,And the validpictureupload method returns a value of true, which will use the binary data of the picture to assign a value to the parameter picture. If the validpictureupload method returns a value of false, the update is cancelled,And exit the event handler.

The code of the validpictureupload (fileupload) method is as follows:

private bool validpictureupload (fileupload pictureupload)
{
 //make sure that a jpg has been uploaded
 if (string.compare (system.io.path.getextension (pictureupload.filename),  ".jpg", true)!=0 &&
 string.compare (system.io.path.getextension (pictureupload.filename),  ".jpeg", true)!=0)
 {
 uploadwarning.text =
  "only jpg documents may be used for a category" s picture. ";
 uploadwarning.visible=true;
 return false;
 }
 else
 {
 return true;
 }
}

Step 8:Replace the original pictures of several categories with jpg format

Recall that the first 8 classes of pictures are bitmap files that contain an ole header. Now we have added new features to edit pictures of existing records,Take a few minutes to replace these bitmap files with jpg files. If i want to make the picture of the current class unchanged,You can convert it to jpg format with the following layout:

1. Save these bitmaps on your hard drive.Visit the updatinganddeleting.aspx page in your browser. For these 8 categories of pictures,Right click and select to save the picture.

2. Open the picture in a picture editor (such as Microsoft Paint) software.

3. Save the picture in jpg format

4. In the editing interface,Update class picture with jpg picture

After updating and uploading jpg images,Pictures are not rendered in the browser,The reason is that displaycategorypicture.aspx will try to strip the ole header for the first 8 categories of pictures. How to fix it?We removed the code that stripped the ole header.In this way, the code of the page_load event handler of the displaycategorypicture.aspx page is as follows:

protected void page_load (object sender, eventargs e)
{
 int categoryid=convert.toint32 (request.querystring ["categoryid"]);
 //get information about the specified category
 categoriesbll categoryapi=new categoriesbll ();
 northwind.categoriesdatatable categories=_
 
 
 response.contenttype="image/jpeg";
 
}

to sum up:Upload files using fileupload

Happy programming!

About the Author

  • Previous CI framework supports two implementation methods of $_GET
  • Next Analysis of CI framework integrated Smarty