DataGrid控件允许用户查看和编辑记录,但内部不包含添加新记录的便利,但是,可以采取不同的方法来添加这个功能。下面的方法包含了如下步骤:
——向DataGrid的数据源(DataSet or DataBase)增加一个新的、空的记录,如果需要的话,还要为记录指定一个ID并为每个不允许为空的列存入一个占位的值。
——重绑定DataGrid到数据源。
——将DataGrid转变为编辑模式,你需要能够知道新记录在DataGrid中显示的位置。
——使用普通的方式更新记录——用户单击“Update”,然后将用户提供的值作为新的记录的值写回到数据源。
下面是添加新记录、绑定DataGrid,以及将其转化为编辑模式的例子。该例中的数据
源是一个DataSet(dsBook1),它包含了一个Books表。
private void btnAddRow_Click(object sender, System.EventArgs e)
{
DataRow dr = this.dsBooks1.Books.NewRow();
dr["title"] = "(New)";
dr["instock"] = true;
this.dsBooks1.Books.Rows.InsertAt(dr, 0);
Session["DsBooks"] = dsBooks1;
DataGrid1.EditItemIndex = 0;
DataGrid1.DataBind();
}
需要注意的一些问题:
——当用户点击也面中的某个“Add”按钮时,这些代码就被执行。
——新行通过NewRow()方法生成,然后通过InsertAt()方法插入到DataSet中的表,该方法允许将该行设定到一个具体的预先确定的位置——在这个例子中,它是表中的第一条记录(也就是Rows集合中的第一行)。换种方式,你也可以通过设置行的数目值将其插入表尾。重要的是,要确切知道该行在表中的位置。
——由于现在你已经知道该行在表中的第一个位置上,你可以通过将DataGrid的编辑项索引设为0,从而将新行设置为编辑模式(如果你在表中的其他位置创建了新行,你可以将编辑项索引设为那个位置的值)。
——现在在数据集中已经有了一条新的记录(但它还不是在数据库中),如果你不想从数据库重新填充DataGrid从而丢失新的记录,就需要在提交—回传的过程中保留一个该数据集的副本。例子中通过代码将其保存在Session中,当页加载时,需要重新从Session中加载数据集。下例是Page_Load()事件句柄的一种可能形式:
private void Page_Load(object sender, System.EventArgs e)
{
if(this.IsPostBack)
{
dsBooks1 = (dsBooks) Session["DsBooks"];
}
else
{
this.sqlDataAdapter1.Fill(this.dsBooks1);
Session["DsBooks"] = dsBooks1;
this.DataGrid1.DataBind();
}
}
你可以通过查看VS文档中的《WEB窗体状态管理》来获得维护状态的信息。
你可以正常更新记录。比如查看VS文档中的概览——使用DataGrid控件读写数据。更
新DataSet后,更新数据库,然后刷新DataSet。要保证再次将刷新后的DataSet保存到Session态。下面是一个更新事件句柄的例子。
private void DataGrid1_UpdateCommand(object source,
System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
dsBooks.BooksRow dr;
//Get a reference to row zero (where the row was inserted)
dr = this.dsBooks1.Books[0];
TextBox tb1 = (TextBox) e.Item.Cells[2].Controls[0];
dr.title = tb1.Text;
CheckBox cb = (CheckBox) e.Item.Cells[3].Controls[1];
dr.instock = cb.Checked;
this.sqlDataAdapter1.Update(this.dsBooks1);
DataGrid1.EditItemIndex = -1;
//Refresh the dataset from the database
dsBooks1.Clear();
this.sqlDataAdapter1.Fill(this.dsBooks1);
//Save the refreshed dataset in Session state agin
Session["DsBooks"] = dsBooks1;
DataGrid1.DataBind();
}