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;
}
}
}