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)
{
//調(diào)用自定義方法綁定數(shù)據(jù)到控件(為以后做MVC打下基礎(chǔ))
BindDataList();
}
}
//對(duì)datelist進(jìn)行數(shù)據(jù)綁定
private void BindDataList()
{
//定義查詢(xún)語(yǔ)句,這里最好將SQL語(yǔ)句在SQL中寫(xiě)好并驗(yàn)證正確確在復(fù)制粘貼過(guò)來(lái)(在對(duì)數(shù)據(jù)查詢(xún)時(shí)最好只查所需的一些不需要的數(shù)據(jù)就不要取出,這樣可以提高運(yùn)行的效率)
string strSql = "SELECT * FROM bg_spatial";//定義一條SQL語(yǔ)句
SqlDataAdapter sda = new SqlDataAdapter(strSql, con);
DataSet ds = new DataSet();
sda.Fill(ds);//把執(zhí)行得到的數(shù)據(jù)放在數(shù)據(jù)集中
DataList1.DataSource = ds;
DataList1.DataBind();
}
protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
{
switch (e.CommandName)
{
//單條數(shù)據(jù)刪除操作
case "delete":
//取得當(dāng)前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();//打開(kāi)數(shù)據(jù)庫(kù)
}
SqlCommand cmd = new SqlCommand(strSQL, con);
if (Convert.ToInt32(cmd.ExecuteNonQuery())>0)
{
Response.Write("script>alert('刪除成功!')/script>");
BindDataList();
}
else
{
Response.Write("script>alert('刪除失??!請(qǐng)查找原因')/script>");
}
con.Close();//關(guān)閉連接
break;
//批量數(shù)據(jù)刪除操作
case "pldelete":
if (con.State.Equals(ConnectionState.Closed))
{
con.Open();//打開(kāi)數(shù)據(jù)庫(kù)
}
DataListItemCollection dlic = DataList1.Items;//創(chuàng)建一個(gè)DataList列表項(xiàng)集合對(duì)象
//執(zhí)行一個(gè)循環(huán)刪除所選中的信息
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;
}
}
}