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
{
////得到Web.config 中的连接放在变量中
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connStr"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//调用自定义方法绑定数据到控件(为以后做MVC打下基础)
BindDataList();
}
}
//对datelist进行数据绑定
private void BindDataList()
{
//定义查询语句,这里最好将SQL语句在SQL中写好并验证正确确在复制粘贴过来(在对数据查询时最好只查所需的一些不需要的数据就不要取出,这样可以提高运行的效率)
string strSql = "SELECT * FROM bg_spatial";//定义一条SQL语句
SqlDataAdapter sda = new SqlDataAdapter(strSql, con);
DataSet ds = new DataSet();
sda.Fill(ds);//把执行得到的数据放在数据集中
DataList1.DataSource = ds;
DataList1.DataBind();
}
protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
{
switch (e.CommandName)
{
//单条数据删除操作
case "delete":
//取得当前Datalist控件列
int id = int.Parse(DataList1.DataKeys[e.Item.ItemIndex].ToString());
string strSQL = "delete from bg_spatial where id='" + id + "'";
if (con.State.Equals(ConnectionState.Closed))
{
con.Open();//打开数据库
}
SqlCommand cmd = new SqlCommand(strSQL, con);
if (Convert.ToInt32(cmd.ExecuteNonQuery())>0)
{
Response.Write("script>alert('删除成功!')/script>");
BindDataList();
}
else
{
Response.Write("script>alert('删除失败!请查找原因')/script>");
}
con.Close();//关闭连接
break;
//批量数据删除操作
case "pldelete":
if (con.State.Equals(ConnectionState.Closed))
{
con.Open();//打开数据库
}
DataListItemCollection dlic = DataList1.Items;//创建一个DataList列表项集合对象
//执行一个循环删除所选中的信息
for (int i = 0; i dlic.Count; i++)
{
if (dlic[i].ItemType == ListItemType.AlternatingItem||dlic[i].ItemType == ListItemType.Item)
{
CheckBox cbox = (CheckBox)dlic[i].FindControl("CheckBox2");
if (cbox.Checked)
{
int p_id = int.Parse(DataList1.DataKeys[dlic[i].ItemIndex].ToString());
SqlCommand p_cmd = new SqlCommand("delete from bg_spatial where id=" + p_id , con);
p_cmd.ExecuteNonQuery();
}
}
}
con.Close();
BindDataList();
break;
}
}
}