In Asp.net, when an operation needs to be completed directly in the background, you can consider adding a general applicationProgram. It is easy to use, for example:
1'. First add a gridview1 and add a general handler named handler. ashx;
2. Add a class named class1, which defines two methods: gettable and DELE.CodeAs follows:
Public static datatable gettable (string SQL)
{
Try
{
Using (sqlconnection sqlcon = new sqlconnection ("Persist Security info = false; user id = sa; Password = 0; database = JP; server = localhost "))
{
Sqlcon. open ();
Sqldataadapter sqd = new sqldataadapter (SQL, sqlcon );
Dataset DS = new dataset ();
Sqd. Fill (DS );
Return Ds. Tables [0];
}
}
Catch
{
}
Return NULL;
}
Public static bool DELE (string SnO)
{
String SQL = "delete from student where SnO = '" + SnO + "'";
Try
{
Using (sqlconnection sqlcon = new sqlconnection ("Persist Security info = false; user id = sa; Password = 0; database = JP; server = localhost "))
{
Sqlcon. open ();
Sqlcommand sqlc = new sqlcommand (SQL, sqlcon );
Sqlc. executenonquery ();
Return true;
}
}
Catch
{
Return false;
}
}
3. gridview1 binds a table named student and the database name is JP. The table content is as follows:
Sno sname ssex ssage field;
99001 Zhang Chen female 20
99002 Li YaoMale 22
Code segment:
Call gettable of class1
protected void page_load (Object sender, eventargs E)
{< br> If (! Ispostback)
{< br> bindstu ();
}
Private void bindstu ()
{
String SQL = "select * from student ";
Datatable dt = class1.gettable (SQL );
This. gridview1.datasource = DT;
This. gridview1.databind ();
}
On the Design page, bind fields such as SnO and sname to the data by setting the datafield attribute of the boundfield in gridview1.
4. Bind the data in grivdview1 with a hyperlinkfield column. The headtext and text names are "deleted", and the sno value is sent to the page handler. aspx.
Specifically, set datanavigatevulfieles of hyperlinfield to sno, and datavavigateurlformats to handler. ashx? Sno = {0 }.
5. Add the following code to handler. ashx to call the DELE method of class1:
<% @ Webhandler Language = "C #" class = "handler" %>
Using system;
Using system. Web;
Public class handler: ihttphandler {
Public void processrequest (httpcontext context)
{
String I = context. Request. querystring ["Sno"]; // Define a string to receive default webpage values;
Try
{ Bool IDs;
IDS = class1.dele (I); // call the delete method;
If (IDS)
{
Context. response. Redirect ("default. aspx"); // after successful, locate the page to default Webpage; }
}
Catch (system. Exception ee)
{
Throw EE;
}
}
Public bool isreusable {
Get {
Return false;
}
}
}
from: http://blog.sina.com.cn/s/blog_60da4e1d0100f8ga.html