65.9K
CodeProject 正在变化。 阅读更多。
Home

在 DataGrid 中执行插入、编辑和更新操作时使用缓存

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.86/5 (21投票s)

2003年1月7日

2分钟阅读

viewsIcon

142228

downloadIcon

7092

本文展示了在 DataGrid 中执行插入、编辑和更新功能时,我们如何使用缓存。

Sample Image - dgcache.gif

引言

这个简单的演示说明了在 DataGrid 中执行插入、编辑和更新功能时,我们如何使用缓存。

步骤说明

DataGrid 还可以显示任何实现 IList 接口的对象。 在这里,为了实现缓存功能,我使用了 ArrayList。 通常,如果想要将数据插入到网格中,可能需要一个表单来接受所有值,然后将其输入到数据库中,并执行选择操作以获取行,然后将其绑定到 DataGrid。 现在,如果使用了 EditCommandColumn,则可能需要对每个修改执行相同的更新和选择操作。 为了最大限度地减少数据库调用并执行所有插入、编辑和更新操作,我们可以使用临时缓存,例如 ArrayList

ArrayList 包含一个名为Props.cs的类的对象,这是我的 Property 类。 它仅包含四个属性:ID、名字、姓氏和城市。

    protected string m_strid;
    protected string m_strfname;
    protected string m_strlname;
    protected string m_strcity;

    public string id 
    {
    get
    {
        return m_strid;
    }
    set 
    {
            m_strid=value;
    }
}

当用户单击“InsertData”时,我获取输入值,创建 Props.cs 类的对象,并将值设置为相应的属性。 然后,我将此对象添加到 ArrayList 并调用一个函数来绑定数据 (NewBindData())。

    props = new Props();
    props.id = strid.Value;
    props.fname = strfname.Value;
    props.lname = strlname.Value;
    props.city = strcity.Value;

    list.Add(props);

    NewBindData();

NewBindData() 方法中,我读取 DataGrid 中的所有项目。 对于 DataGrid 中的每个项目(DataGrid 中的一行),我都创建一个 Props.cs 类的实例,并将相应属性设置为相应单元格的值。 在为每个项目填写了 Props.cs 类中的属性后,我将其添加到数组列表中。

foreach(DataGridItem item in DataGrid1.Items) 
{
    props = new Props();

    //to read the ItemTemplate
    if(!item.ItemType.ToString().Equals("EditItem"))
    {
    props.id = ((Label)item.Cells[1].FindControl("Label1")).Text;
    props.fname = ((Label)item.Cells[2].FindControl("Label2")).Text;
    props.lname = ((Label)item.Cells[3].FindControl("Label3")).Text;
    props.city = ((Label)item.Cells[4].FindControl("Label4")).Text;
    }
    //to read the EditItemTemplate
    else if(item.ItemType.ToString().Equals("EditItem")) 
    {
    props.id = ((TextBox)item.Cells[1].FindControl("Textbox1")).Text;
    props.fname = ((TextBox)item.Cells[2].FindControl("Textbox2")).Text;
    props.lname = ((TextBox)item.Cells[3].FindControl("Textbox3")).Text;
    props.city = ((TextBox)item.Cells[4].FindControl("Textbox4")).Text;
    }

    list.Add(props);
}

读取 DataGrid 中的所有项目并将它们作为属性对象填充到 ArrayList 中后,我将 DataGridDataSource 设置为此 ArrayList 并绑定数据。

    DataGrid1.DataSource = list;
    DataGrid1.DataBind();

因此,每次插入都会重复此过程。 在我的 DataGrid 中,我使用 EditCommandColumn 来执行编辑和更新功能。 每当单击编辑列时,它都会引用代码隐藏页中的 OnEdit() 函数,我所做的只是设置编辑项索引并调用该函数来绑定数据 (NewBindData())。

    protected void OnEdit(object source, 
          System.Web.UI.WebControls.DataGridCommandEventArgs e)
    {
    DataGrid1.EditItemIndex = e.Item.DataSetIndex;
    NewBindData();
    }

同样,对于更新和取消,我将编辑项索引设置为默认值 (-1) 并调用该函数来绑定数据 (NewBindData())。

    DataGrid1.EditItemIndex = -1;
    NewBindData();

结论

对于所有插入、编辑和更新操作,我们根本没有使用任何数据库操作。 您可以在页面的末尾放置一个提交按钮,上面写着“提交所有更改”。 单击此按钮后,您可以执行一次性数据库操作。

© . All rights reserved.