using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class _Default : System.Web.UI.Page
{
//private SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Sql"].ToString());
private SqlConnection conn = new SqlConnection("server=(local);uid=sa;pwd=sa;database=union_5k3g;");
protected void Page_Load(object sender, EventArgs e)
{
conn.Open();
if (!IsPostBack)
{
BindData();
}
}
protected void Page_UnLoad(object sender, EventArgs e)
{
conn = null;
}
private void BindData()
{
SqlDataAdapter sda = new SqlDataAdapter("Select Top 10 * From Union_User order By ID Desc", conn);
DataSet ds = new DataSet();
sda.Fill(ds, "Union_User");
DataList1.DataSource = ds.Tables["Union_User"].DefaultView;
DataList1.DataBind();
}
protected void DataList1_Cancel(object source, DataListCommandEventArgs e)
{
DataList1.EditItemIndex = -1;
BindData();
}
protected void DataList1_Delete(object source, DataListCommandEventArgs e)
{
string id = DataList1.DataKeys[e.Item.ItemIndex].ToString();
SqlCommand cmd = new SqlCommand("Delete From Union_User Where ID=" + id, conn);
cmd.ExecuteNonQuery();
DataList1.EditItemIndex = -1;
BindData();
}
protected void DataList1_Edit(object source, DataListCommandEventArgs e)
{
DataList1.EditItemIndex = e.Item.ItemIndex;
BindData();
}
protected void DataList1_Update(object source, DataListCommandEventArgs e)
{
string loginname = ((TextBox)e.Item.FindControl("TextBox1")).Text;
string website = ((TextBox)e.Item.FindControl("TextBox2")).Text;
string id = DataList1.DataKeys[e.Item.ItemIndex].ToString();
SqlCommand cmd = new SqlCommand("Update Union_User Set LoginName='" + loginname + "',WebSite='" + website + "' Where ID=" + id, conn);
cmd.ExecuteNonQuery();
DataList1.EditItemIndex = -1;
BindData();
}
}
4.注意事项
1).获取DataList模板中TextBox中的值必须使用"((TextBox)e.Item.FindControl("TextBox1")).Text",直接使用"TextBox1.Text"将出错提示:CS0103: 当前上下文中不存在名称“TextBox1”;