(将自己平时学到的东西谨在此做个记录,以备以后查询参考之用)
在后台代码编辑之前,需要设置:
1. DataList的ID:dlCategory, DataKeyField="CategoryID"
2. Item Templat中 ,两个label分别显示(Text属性),CategoryID,CategoryName
Item Templat中 ,两个TextBox分别设置(ID属性),txtCategoryID,txtCategoryName,另外需要绑定数据,即在EditDataBinding中的Text项输入:DataBinder.Eval(Container. DataItem,"CategoryID")/Eval("CategoryID")
Item Templat中 ,四个个Button分别设置。ID属性,Text属性,CommandName属性(important)
select,update,cancle,delete.在dlCategory_ItemCommand()方法中,用于判断执行的操作。
3.该代码还需用到MVC三层架构的东西,参考MVC文章。


{
if (!IsPostBack)
{
Bind(); //更新页面数据
}
}
private void Bind() //定义方法,加载数据源,绑定数据
{
ItemCategoryBLL categoryBLL = new ItemCategoryBLL(); //实例化BLL
dlCategory.DataSource = null;
dlCategory.DataSource = categoryBLL.GetAllCategoryList(); //加载数据源
dlCategory.DataBind(); //绑定数据
}
protected void dlCategory_ItemCommand(object source, DataListCommandEventArgs e)//在ItemCommand方法中写入
{
if(e.CommandName=="update")
{
ItemCategoryBLL categoryBLL=new ItemCategoryBLL();
dlCategory.EditItemIndex=e.Item.ItemIndex;
string categoryName = ((TextBox)e.Item.FindControl("txtCategoryName")).Text;
//获取当前编辑行的CategoryName列中的数据
int categoryID = Convert.ToInt32(((TextBox)e.Item.FindControl("txtCategoryID")).Text);
//获取当前编辑行的CategoryID列中的数据
categoryBLL.UpdateCategory(categoryName,categoryID);//实例化后的BLL调用Update方法
Bind(); //重新更新页面数据
}
else if (e.CommandName=="cancle")
{
dlCategory.EditItemIndex = -1;//设置DataList控件的编辑项的索引为-1,取消编辑
Bind();
}
else if (e.CommandName == "delete")
{
ItemCategoryBLL categoryBLL = new ItemCategoryBLL();
dlCategory.EditItemIndex = e.Item.ItemIndex;
int categoryID = Convert.ToInt32(((TextBox)e.Item.FindControl("txtCategoryID")).Text);
int i= categoryBLL.DeleteCategory(categoryID);
if(i!=0)
{
Bind();
}