我有一个可编辑的 Gridview,它使用 XML 文件运行。当我尝试通过 Gridiview 更新/删除一行时,XML 文件中的所有数据都会被删除。当我插入新行时,挂起的数据将被新行替换。我可以就我做错了什么得到一些指导吗?我提供了我的 xml 文件和用于编辑 GridView 的四种方法。
XML:
<root>
<pos>
<partNumbers>
<partid>0</partid>
<partnumber>796542</partnumber>
</partNumbers>
<partNumbers>
<partid>1</partid>
<partnumber>225614</partnumber>
</partNumbers>
<partNumbers>
<partid>2</partid>
<partnumber>123457</partnumber>
</partNumbers>
</pos>
</root>
源代码-C#-:
//Bind Data
protected void BindGridView()
{
DataSet dsgvPartNumber = new DataSet();
dsgvPartNumber.ReadXml(Server.MapPath("~/xml/storeUserInfo.xml"));
gvPartNumber.DataSource = dsgvPartNumber.Tables["partNumbers"];
gvPartNumber.DataBind();
gvPartNumber.ShowFooter = true;
}
//Delete
protected void gvPartNumber_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
BindGridView();
DataTable dsgvPartNumberDelete = (DataTable)gvPartNumber.DataSource;
dsgvPartNumberDelete.Rows[gvPartNumber.Rows[e.RowIndex].DataItemIndex].Delete();
dsgvPartNumberDelete.WriteXml(Server.MapPath("~/xml/storeUserInfo.xml"));
BindGridView();
}
//Update GridView
protected void gvPartNumber_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int index = gvPartNumber.Rows[e.RowIndex].DataItemIndex;
string partId = ((TextBox)gvPartNumber.Rows[e.RowIndex].FindControl("txtPartID")).Text;
string partNumber = ((TextBox)gvPartNumber.Rows[e.RowIndex].FindControl("txtPartNumber")).Text;
gvPartNumber.EditIndex = -1;
BindGridView();
DataTable dtUpdateXMLFile = (DataTable)gvPartNumber.DataSource;
dtUpdateXMLFile.Rows[index]["partid"] = partId;
dtUpdateXMLFile.Rows[index]["partnumber"] = partNumber;
dtUpdateXMLFile.WriteXml(Server.MapPath("~/xml/storeUserInfo.xml"));
BindGridView();
}
//Insert New Row
protected void gvPartNumber_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "insertXMLData")
{
string partid = ((TextBox)gvPartNumber.FooterRow.FindControl("txtPartIDInsert")).Text;
string partnumber = ((TextBox)gvPartNumber.FooterRow.FindControl("txtPartNumberInsert")).Text;
BindGridView();
DataTable dtXMLInsert = (DataTable)gvPartNumber.DataSource;
DataRow drInsert = dtXMLInsert.NewRow();
drInsert["partid"] = partid;
drInsert["partnumber"] = partnumber;
dtXMLInsert.Rows.Add(drInsert);
dtXMLInsert.WriteXml(Server.MapPath("~/xml/storeUserInfo.xml"));
BindGridView();
}
}