jquery html div+css
当前位置:EXT之家 >>asp-net>> 列表

ASP.NET之GridView(2)【自定义】

来源:网络    编辑:admin

      在(1)提到了如何不编写任何代码实现GridView对数据编辑、分页、删除等功能,但是这种操作存在很大的弊端———SQL语句写在了HTML页面。这样一来造成很大安全隐患,做出的程序很容易会被攻破。当然可以对语句进行加密,另一种就是让SQL语句分离出来(这就用到了自定义GridView——通过编写一些代码来实现各项功能)

GridView控件6种常见类型的列:捕获

源码示例:

.aspx界面:

<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="学号" />
<asp:BoundField DataField="st_name" HeaderText="姓名" />
<asp:BoundField DataField="st_gender" HeaderText="性别" />
<asp:BoundField DataField="st_address" HeaderText="地址" />
<asp:BoundField DataField="st_tel" HeaderText="联系电话" />
<asp:BoundField DataField="st_nation" HeaderText="国家" />
<asp:CommandField HeaderText="选择" ShowSelectButton="True" />
<asp:CommandField ButtonType="Image" CancelImageUrl="~/Images/BtnCancel.gif"
EditImageUrl="~/Images/BtnUpdate.gif" HeaderText="编辑" ShowEditButton="True"
UpdateImageUrl="~/Images/BtnSave.gif" />
<asp:TemplateField HeaderText="删除" ShowHeader="False">
<ItemTemplate>
<asp:ImageButton ID="ImageButton1" runat="server" CommandName="Delete"
ImageUrl="~/Images/BtnDelete.gif"
onclientclick="return confirm("确定删除吗?");" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<%--设置GridView样式,这里是套用内置的样式,在设置界面可以选择自动调用样式--%>
<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界面:



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)
{
//调用自定义方法绑定数据到控件(为以后做MVC打下基础)
BindData();
}
}
private void BindData()
{
//这里将数据库连接字符串写在web.config文件中,通过这个语句来调用,这样方便对连接字符串的修改
string connStr = ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
//创建数据库连接对象
SqlConnection con = new SqlConnection(connStr);
//定义查询语句,这里最好将SQL语句在SQL中写好并验证正确确在复制粘贴过来(在对数据查询时最好只查所需的一些不需要的数据就不要取出,这样可以提高运行的效率)
string sql = "select * from student";
//创建适配器(自动打开关闭数据库)
SqlDataAdapter dt = new SqlDataAdapter(sql, con);
//创建数据集
DataSet ds = new DataSet();
//填充数据集
dt.Fill(ds);
//设置GridView控件的数据源为定义的数据集ds
GridView1.DataSource = ds;
//将数据表中的主键字段放置到GridView控件中的DataKeyNames属性中
GridView1.DataKeyNames = new string[] { "st_id" };
//绑定数据库表中数据
GridView1.DataBind();
}

#region 用来执行SQL语句
/// <summary>
/// 用来执行SQL语句
/// </summary>
/// <param name="strSqlCom"></param>
/// <returns></returns>
public bool ExceSQL(string strSqlCom)
{
//定义数据库连接字符串
string strCon = ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
//创建数据库连接对象
SqlConnection sqlcon = new SqlConnection(strCon);
SqlCommand sqlcom = new SqlCommand(strSqlCom, sqlcon);
try
{
//判断数据库是否为连连状态
if (sqlcon.State == System.Data.ConnectionState.Closed)
{ sqlcon.Open(); }
//执行SQL语句
sqlcom.ExecuteNonQuery();
//SQL语句执行成功,返回true值
return true;
}
catch
{
//SQL语句执行失败,返回false值
return false;
}
finally
{
//关闭数据库连接
sqlcon.Close();
}
}
#endregion



protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
//获取编辑行的索引
GridView1.EditIndex = e.NewEditIndex;
BindData();//数据绑定
}

#region 单击修改后所触发的事件
/// <summary>
/// 单击修改后所触发的事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//取得编辑行的关键字段的值
string st_id = GridView1.DataKeys[e.RowIndex].Value.ToString();
//取得文本框中输入的内容
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();
//定义更新操作的sql语句
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);//调用ExceSQL执行更新操作
if (b)
{
Response.Write("<script language=javascript>alert("修改成功!")</script>");
//设置控件编辑项的索引值为—1 ,即取消编辑
GridView1.EditIndex = -1;
BindData();
}
else
{
Response.Write("<script language=javascript>alert("修改失败!")</script>");
}
}
#endregion

#region 点即取消按钮所触发的事件
/// <summary>
/// 点即取消按钮所触发的事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
//设置控件编辑项的索引值为—1 ,即取消编辑
GridView1.EditIndex = -1;
BindData();
}
#endregion

#region 点击删除按钮时所触发的事件
/// <summary>
/// 点击删除按钮时所触发的事件
/// </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);//调用ExceSQL执行删除操作
if (delete)
{
Response.Write("<script language=javascript>alert("删除成功!")</script>");
BindData();//调用自定义方法重新绑定控件中数据
}
else
{
Response.Write("<script language=javascript>alert("删除失败!")</script>");
}
}
#endregion

#region 用来设置分页的事件
/// <summary>
/// 用来设置分页的事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void GridView1_PageIndexChanging1(object sender, GridViewPageEventArgs e)
{
//获取当前分页索引值
GridView1.PageIndex = e.NewPageIndex;
//重新绑定数据
BindData();
}
#endregion

}
版权所有:jory—经得起折磨,耐得住寂寞



















































































































































































































































































来源:网络    编辑:admin

相关栏目

导航

Ext教程 Web开发 经典asp android mssql vb 杂七杂八