Asp.net 2.0 practice (2) Add the custom control of date selection and Image Upload modification to the gridview or detailsview _ jaye.net

Source: Internet
Author: User
1. Date Selection Control

The date field input in the gridview is really troublesome, because for general users, they do not know the format of the input date, if the date input is not a text input but selected from the calendar control, it will be much better.

Create a custom control.

1. Create a simple custom date Selection Control

In the visual window, place a Textbox, a button, and a calendar control.

Source code for pickdate. ascx:

<% @ Control Language = "C #" autoeventwireup = "true" codefile = "pickdate. ascx. cs" inherits = "pickdate" %>
& Nbsp; <asp: textbox id = "tbdate" runat = "server" width = "83px"> </ASP: textbox> <asp: button
Id = "button1" runat = "server" onclick = "button#click" text = "Courier" tooltip = "date selector"
Width = "29px"/>
<Asp: Calendar id = "calendar1" runat = "server" Height = "149px" onselectionchanged = "calendar#selectionchanged"
Width = "157px" backcolor = "# ffffcc" bordercolor = "# ffcc66" borderwidth = "1px" daynameformat = "shortest" font-names = "verdana" font-size = "8pt "forecolor =" #663399 "showgridlines =" true "visible =" false ">
<Selecteddaystyle backcolor = "# ccccff" font-bold = "true"/>
<Selectorstyle backcolor = "# ffcc66"/>
<Othermonthdaystyle forecolor = "# cc9966"/>
<Todaydaystyle backcolor = "# ffcc66" forecolor = "white"/>
<Nextprevstyle font-size = "9pt" forecolor = "# ffffcc"/>
<Dayheaderstyle backcolor = "# ffcc66" font-bold = "true" Height = "1px"/>
<Titlestyle backcolor = "#990000" font-bold = "true" font-size = "9pt" forecolor = "# ffffcc"/>
</ASP: Calendar>

Set necessary attributes and event handling in codefile

The reference code is as follows:

Using system;
Using system. Data;
Using system. configuration;
Using system. collections;
Using system. Web;
Using system. Web. Security;
Using system. Web. UI;
Using system. Web. UI. webcontrols;
Using system. Web. UI. webcontrols. webparts;
Using system. Web. UI. htmlcontrols;

Public partial class pickdate: system. Web. UI. usercontrol
{
Private datetime m_thisdate; // redundant

Public datetime thisdate
{
Get {
If (tbdate. Text! = String. Empty)
{
Return datetime. parse (tbdate. Text );
}
Else
{
Return datetime. Now. date;
}

}
Set {

Tbdate. Text = value. Date. to1_datestring (); // you do not need to judge value because it must be of the date type.
Calendar1.selecteddate = value;
Calendar1.visibledate = value;
}
}

Protected void page_load (Object sender, eventargs E)
{

}
Protected void calendar1_selectionchanged (Object sender, eventargs E)

{
Tbdate. Text = calendar1.selecteddate. tow.datestring ();;
}
Protected void button#click (Object sender, eventargs e) // manipulate the visual status of the calendar
{
Calendar1.visible =! Calendar1.visible;
If (calendar1.visible)
{
Button1.text = "▲ ";
}
Else
{
Button1.text = "success ";
}
}
}

2. Convert the columns to the template using this control, and then place the control in the edit template to bind it to the source code view (the visual status cannot be bound, because the thisdate attribute is not displayed in the bound property options)

<Edititemtemplate>

<Uc1: pickdate id = "pickdate1" runat = "server" thisdate = '<% # BIND ("begindate") %>'/>

</Edititemtemplate>

OK. in this way, you can use the date Selection Method in the gridview to enter a date. The disadvantage is that the field of the corresponding database must be date and have a value, otherwise, the binding error ("specified cast is not valid. "), trying to judge whether the value is null (if (value = NULL), but it is useless. The breakpoint setting error occurs before the attribute setting (SET), and the error occurs in <uc1: pickdate id = "pickdate1" runat = "server" thisdate = '<% # BIND ("begindate") %>'/>

I hope you will inform us of the solution.

Ii. Image Upload Control

 

1. Add template to the gridview or detailsview

<Itemtemplate>
<Uc1: imageupload id = "imageupload1" runat = "server" thisphoto = '<% # eval ("username ") %> 'alt = '<% # eval ("des") %>'/>
</Itemtemplate>

Similarly, the binding needs to be changed in the source code. The thisphoto and ALT attributes cannot be found in the visual binding.

2. Processing sqldatasource

As you can see, when you move the mouse over the image, the image description is actually the alt attribute, which is certainly read from the database. So how can we make datasource generate this description field?

One way is to use objectdatasource (see my first article ).

Asp.net 2.0 practice (1) _ creating a custom dynamic news LIST _ jaye.net

)

But in fact, objectdatasource is not required here (it is better to use and better to control the format), and sqldatasource can also be used. As follows:

<Asp: sqldatasource id = "sqldatasource1" runat = "server" connectionstring = "<% $ connectionstrings: bobbyconnectionstring %>"
Selectcommand = "select [username], 'des '= 'user name:' + [username] + char (13) + 'address:' + [ADDR] + char (13) + 'phone: '+ [PHONE] + char (13) + 'qq:' + [QQ] + char (13) + 'ID card: '+ [IC] + char (13) from [user_detail] Where ([username] = @ username) ">
<Selectparameters>
<Asp: controlparameter controlid = "textbox2" name = "username" propertyname = "text" type = "string"/>
</Selectparameters>
</ASP: sqldatasource>

Create a 'des 'field in the SELECT statement of selectcommand. This field is a combination of other actually existing Description fields.

3. Design Custom Controls

For details about imageupload. ascx, refer:

<% @ Control Language = "C #" autoeventwireup = "true" codefile = "imageupload. ascx. cs" inherits = "imageupload" %>
<Asp: Panel id = "Panel1" runat = "server" Height = "198px" width = "204px">
& Nbsp;
<Asp: Image id = "imageud" runat = "server" Height = "184px" width = "180px"/>
<Asp: fileupload id = "fileuploadimage" runat = "server"/>
<Asp: button id = "buttonupload" runat = "server" onclick = "buttonupload_click" text = "Upload"/>
<Asp: Label id = "labelimage" runat = "server" forecolor = "# ffc0c0"> </ASP: Label> </ASP: Panel>

For imageupload. ascx. CS, refer:

Using system;
Using system. Data;
Using system. configuration;
Using system. collections;
Using system. Web;
Using system. Web. Security;
Using system. Web. UI;
Using system. Web. UI. webcontrols;
Using system. Web. UI. webcontrols. webparts;
Using system. Web. UI. htmlcontrols;

Public partial class imageupload: system. Web. UI. usercontrol
{
Protected void page_load (Object sender, eventargs E)
{

}
Private string m_thisphoto; // extra variable
Public String thisphoto // address attribute of the image
{
Get {
Return imageud. imageurl;
}
Set {
Imageud. imageurl = "~ /Login/userphotohandler. ashx? Id = "+ value +" & size = 100 "; // you can use ashx to manipulate the image. In brief, you can use ashx to obtain the image.
}
}
Private string m_alt; // extra variable
Public String alt // The ALT attribute of the image
{
Get
{
Return imageud. alternatetext;
}
Set
{
Imageud. alternatetext = value;
}
}
Protected void buttonupload_click (Object sender, eventargs e) // simple code for uploading images
{
If (fileuploadimage. hasfile & (fileuploadimage. filename. tolower (). endswith ("jpg") | fileuploadimage. filename. tolower (). endswith ("Jpeg ")))
Try
{
Fileuploadimage. saveas (mappath ("~ /Photo/") + membership. getuser (). username +". jpg ");
Labelimage. Text = "image modified ";

}
Catch (exception ex)
{
Labelimage. Text = "error ";
}
Else
{
Labelimage. Text = "select a local image. Currently, only JPG format is accepted ";
}
}
}
 

4. Use the ashx (userphotohandler. ashx) middle layer to prevent images from being downloaded in batches without putting the images in the database.

In fact, there is ashx in the Asp.net 1.1 era. but I never knew that aspx was used to implement the current functions. I personally felt that there was no difference in implementation and the performance was not clear (it should be strong in ashx, at least ashx does not need to process the interface ).

Ashx is used to extract image data from an existing database, or process the image on the server and output it as an image.

(1) ashx is used to extract image data from the existing database: I tried to read the image from the northwind (SQL Server2000), but it was unsuccessful. For details, see my blog:

[Help] Why is it wrong to use ashx to read images from northwind?

(2) process the server image and output it as an image. The following is the reference code:

Public void processrequest (httpcontext context ){
Context. response. contenttype = "image/JPEG ";
Context. response. cache. setcacheability (httpcacheability. Public );
Context. response. bufferoutput = false;

String strfilename;
Int bytesread, intfilelength;
Byte [] bytevalues;
System. Drawing. Image imgfullsize, imglastsize;
Memorystream stmimage;
Strfilename = context. server. mappath ("~ /Photo/"+ context. request. querystring ["ID"] + ". jpg "); // The URL attribute of the image. Here, because I am a username with only one corresponding image, a special imageurl is usually required for this processing.
Imgfullsize = system. Drawing. image. fromfile (strfilename );
Int intsize;
Intsize = int. parse (context. Request. Params ["size"]); // The width of the uploaded image,
Imglastsize = imgfullsize. getthumbnailimage (intsize, imgfullsize. Width * imgfullsize. Height/intsize, null, intptr. Zero );

Stmimage = new memorystream ();
Imglastsize. Save (stmimage, system. Drawing. imaging. imageformat. JPEG );
Intfilelength = convert. toint32 (stmimage. Length );
Bytevalues = new byte [intfilelength];
Stmimage. Position = 0;
Bytesread = stmimage. Read (bytevalues, 0, intfilelength );
If (bytesread> 0)
{
Context. response. binarywrite (bytevalues );
}
Stmimage. Close ();
// Context. response. End ();

}

 

OK. please correct me.

Related Article

Contact Us

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.