ASP. NET GridView (2) [custom]

Source: Internet
Author: User

In (1) Commit. In this way, a great security risk is caused, and the program is easily cracked. Of course, the statement can be encrypted, and the other is to separate the SQL statement (this uses the custom GridView-to implement various functions by writing some code)
The GridView control has six common types of columns:
Source code example:
. Aspx interface:
 

<Body>
<Form id = "form1" runat = "server">
<Div>

<Asp: GridView ID = "GridView1" runat = "server" AllowPaging = "True" CellPadding = "4"
ForeColor = "#333333" GridLines = "None"
Onpageindexchanging = "GridView1_PageIndexChanging1" PageSize = "5"
AutoGenerateColumns = "False"
Onrowcancelingedit = "GridView1_RowCancelingEdit"
Onrowdeleting = "GridView1_RowDeleting" onrowediting = "GridView1_RowEditing"
Onrowupdating = "GridView1_RowUpdating">
<AlternatingRowStyle BackColor = "White"/>
<Columns>
<Asp: BoundField DataField = "st_id" HeaderText = "student ID"/>
<Asp: BoundField DataField = "st_name" HeaderText = "name"/>
<Asp: BoundField DataField = "st_gender" HeaderText = "gender"/>
<Asp: BoundField DataField = "st_address" HeaderText = "Address"/>
<Asp: BoundField DataField = "st_tel" HeaderText = "contact number"/>
<Asp: BoundField DataField = "st_nation" HeaderText = "country"/>
<Asp: CommandField HeaderText = "select" ShowSelectButton = "True"/>
<Asp: CommandField ButtonType = "Image" CancelImageUrl = "~ /Images/BtnCancel.gif"
EditImageUrl = "~ /Images/BtnUpdate.gif "HeaderText =" edit "ShowEditButton =" True"
UpdateImageUrl = "~ /Images/BtnSave.gif "/>
<Asp: TemplateField HeaderText = "delete" ShowHeader = "False">
<ItemTemplate>
<Asp: ImageButton ID = "ImageButton1" runat = "server" CommandName = "Delete"
ImageUrl = "~ /Images/BtnDelete.gif"
Onclientclick = "return confirm ('Are you sure you want to delete it? '); "/>
</ItemTemplate>
</Asp: TemplateField>
</Columns>
<% -- Set the GridView style. Here, the built-in style is applied. On the settings page, you can choose to automatically call the style -- %>
<FooterStyle BackColor = "#990000" Font-Bold = "True" ForeColor = "White"/>
<HeaderStyle BackColor = "#990000" Font-Bold = "True" ForeColor = "White"/>
<PagerStyle BackColor = "# FFCC66" ForeColor = "#333333" HorizontalAlign = "Center"/>
<RowStyle BackColor = "# FFFBD6" ForeColor = "#333333"/>
<SelectedRowStyle BackColor = "# FFCC66" Font-Bold = "True" ForeColor = "Navy"/>
<SortedAscendingCellStyle BackColor = "# FDF5AC"/>
<SortedAscendingHeaderStyle BackColor = "#4D0000"/>
<SortedDescendingCellStyle BackColor = "# FCF6C0"/>
<SortedDescendingHeaderStyle BackColor = "#820000"/>
</Asp: GridView>

</Div>
</Form>
</Body>
. Cs interface:
Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Web;
Using System. Web. UI;
Using System. Web. UI. WebControls;
Using System. Data;
Using System. Data. SqlClient;
Using System. Configuration;
 
Public partial class _ Default: System. Web. UI. Page
{
Protected void Page_Load (object sender, EventArgs e)
{
If (! IsPostBack)
{
// Call a custom method to bind data to the control (laying the foundation for future MVC)
BindData ();
}
}
Private void BindData ()
{
// Write the database connection string in the web. config file and use this statement to modify the connection string.
String connStr = ConfigurationManager. ConnectionStrings ["connStr"]. ConnectionString;
// Create a database connection object
SqlConnection con = new SqlConnection (connStr );
// Define the query statement, it is best to write the SQL statement in the SQL statement and verify that the SQL statement is correctly copied and pasted. (when querying data, it is best not to retrieve the unnecessary data, this improves the running efficiency)
String SQL = "select * from student ";
// Create an adapter (automatically turn on and off the database)
SqlDataAdapter dt = new SqlDataAdapter (SQL, con );
// Create a dataset
DataSet ds = new DataSet ();
// Fill in the dataset www.2cto.com
Dt. Fill (ds );
// Set the data source of the GridView control as the defined data set ds
GridView1.DataSource = ds;
// Place the primary key field in the data table to the DataKeyNames attribute in the GridView control.
GridView1.DataKeyNames = new string [] {"st_id "};
// Bind the data in the database table
GridView1.DataBind ();
}
 
# Region is used to execute SQL statements
/// <Summary>
/// Used to execute SQL statements
/// </Summary>
/// <Param name = "strSqlCom"> </param>
/// <Returns> </returns>
Public bool ExceSQL (string strSqlCom)
{
// Define the database connection string
String strCon = ConfigurationManager. ConnectionStrings ["connStr"]. ConnectionString;
// Create a database connection object
SqlConnection sqlcon = new SqlConnection (strCon );
SqlCommand sqlcom = new SqlCommand (strSqlCom, sqlcon );
Try
{
// Determine whether the database is in the connected status
If (sqlcon. State = System. Data. ConnectionState. Closed)
{Sqlcon. Open ();}
// Execute the SQL statement
Sqlcom. ExecuteNonQuery ();
// Returns true if the SQL statement is successfully executed.
Return true;
}
Catch
{
// If an SQL statement fails to be executed, false is returned.
Return false;
}
Finally
{
// Close the database connection
Sqlcon. Close ();
}
}
# Endregion

 

Protected void gridviewinclurowediting (object sender, GridViewEditEventArgs e)
{
// Obtain the index of the edited row
GridView1.EditIndex = e. NewEditIndex;
BindData (); // bind data
}
 
# Region click the event triggered after modification
/// <Summary>
/// Click the event triggered after the modification
/// </Summary>
/// <Param name = "sender"> </param>
/// <Param name = "e"> </param>
Protected void GridView1_RowUpdating (object sender, GridViewUpdateEventArgs e)
{
// Obtain the value of the key field of the edit row
String st_id = GridView1.DataKeys [e. RowIndex]. Value. ToString ();
// Obtain the content entered in the text box
String st_name = (TextBox) (GridView1.Rows [e. RowIndex]. Cells [1]. Controls [0]). Text. ToString (). Trim ();
String st_gender = (TextBox) (GridView1.Rows [e. RowIndex]. Cells [2]. Controls [0]). Text. ToString (). Trim ();
String st_address = (TextBox) (GridView1.Rows [e. RowIndex]. Cells [3]. Controls [0]). Text. ToString (). Trim ();
String st_tel = (TextBox) (GridView1.Rows [e. RowIndex]. Cells [4]. Controls [0]). Text. ToString (). Trim ();
String st_nation = (TextBox) (GridView1.Rows [e. RowIndex]. Cells [5]. Controls [0]). Text. ToString (). Trim ();
// Define the SQL statement for the update operation
String update = "update student set st_name = '" + st_name + "', st_gender = '" + st_gender + "', st_address = '" + st_address + "', st_tel = '"+ st_tel +"', st_nation = '"+ st_nation +" 'where st_id =' "+ st_id + "'";
Bool B = ExceSQL (update); // call ExceSQL to perform the update operation
If (B)
{
Response. Write ("<script language = javascript> alert ('modification successful! ') </Script> ");
// Set the index value of the control editing item to-1, that is, cancel editing.
GridView1.EditIndex =-1;
BindData ();
}
Else
{
Response. Write ("<script language = javascript> alert ('modification failed! ') </Script> ");
}
}
# Endregion

# Events triggered by the region point, that is, the cancel button
/// <Summary>
/// Click the event triggered by the cancel button
/// </Summary>
/// <Param name = "sender"> </param>
/// <Param name = "e"> </param>
Protected void GridView1_RowCancelingEdit (object sender, GridViewCancelEditEventArgs e)
{
// Set the index value of the control editing item to-1, that is, cancel editing.
GridView1.EditIndex =-1;
BindData ();
}
# Endregion

# Events triggered when region clicks the delete button
/// <Summary>
/// Events triggered when the delete button is clicked
/// </Summary>
/// <Param name = "sender"> </param>
/// <Param name = "e"> </param>
///
Protected void GridView1_RowDeleting (object sender, GridViewDeleteEventArgs e)
{
String delete_ SQL = "delete from student where st_id = '" + GridView1.DataKeys [e. RowIndex]. Value. ToString () + "'";
Bool delete = ExceSQL (delete_ SQL); // call ExceSQL to perform the delete operation
If (delete)
{
Response. Write ("<script language = javascript> alert ('deleted successfully! ') </Script> ");
BindData (); // call the custom method to re-bind the data in the control
}
Else
{
Response. Write ("<script language = javascript> alert ('deletion failed! ') </Script> ");
}
}
# Endregion
 
# Region used to set paging events
/// <Summary>
/// Used to set paging events
/// </Summary>
/// <Param name = "sender"> </param>
/// <Param name = "e"> </param>
Protected void GridView1_PageIndexChanging1 (object sender, GridViewPageEventArgs e)
{
// Obtain the index value of the current page
GridView1.PageIndex = e. NewPageIndex;
// Rebind data
BindData ();
}
# Endregion

}

 

From jory
 

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.