C#用datagriview控件增加删除行数据,并且更新到xml中,求代码(急)如图

如题所述

完全按你的要求写的,供参考:

前提是XML文件已创建好,在窗体里选择该XML文件,再行操作:

窗体:

 //选择XML按钮
        private void btnXML_Click(object sender, EventArgs e)
        {
            DataTable dt = new DataTable();
            OpenFileDialog xmlFile = new OpenFileDialog();
            xmlFile.Filter = "*.xml|";
            xmlFile.Title = "请选择xml文件";
            if (xmlFile.ShowDialog() == DialogResult.OK)
            {
                this.txtPath.Text = xmlFile.FileName;//在textBox1控件中显示选择的路径
                dt=GetXML(this.txtPath.Text);
            }
            if(!dt.Equals(null)&&dt.Rows.Count>0)
            LoadData(dt, dgvXML);//加载到窗体中
        }
        //保存按钮
        private void button1_Click(object sender, EventArgs e)
        {
            int n = SaveDgv();
            if (n > 0)
            {
                MessageBox.Show("保存成功!");
                DataTable dt = new DataTable();
                dt = GetXML(this.txtPath.Text);
                LoadData(dt, dgvXML);//刷新加载
            }
            else
            {
                MessageBox.Show("保存失败!");
                DataTable dt = new DataTable();
                dt = GetXML(this.txtPath.Text);
                LoadData(dt, dgvXML);//刷新加载
            }
        }
        //删除按钮
        private void btnDelete_Click(object sender, EventArgs e)
        {
            int n = 0;//判断是否删除
            for (int i = 0; i < dgvXML.SelectedRows.Count; i++)
            {
                string id = dgvXML.SelectedRows[i].Cells[0].Value.ToString();
                XmlDocument doc = new XmlDocument();
                doc.Load(this.txtPath.Text);
                XmlNodeList nod = doc.DocumentElement.ChildNodes;
                XmlNode root = doc.DocumentElement;
                foreach (XmlNode peo in nod)
                {
                    if (XmlNode.Equals(peo.SelectSingleNode("ID").InnerText, id))
                    {
                        root.RemoveChild(peo);//从根节点删除该ID的PERSON
                        doc.Save(this.txtPath.Text);
                        n++;
                    }
                }
            }
            if (n > 0)
            {
                DataTable dt = new DataTable();
                dt = GetXML(this.txtPath.Text);
                LoadData(dt, dgvXML);//刷新加载
                MessageBox.Show("删除成功!");
            }
            else
            {
                MessageBox.Show("删除失败!");
            }
            
        }
        // DataGridView中加载数据
        private void LoadData(DataTable dt, DataGridView dgv)
        {
            dgv.Rows.Clear();//datagridview清空数据
            if (dt != null && dt.Rows.Count > 0)
            {
                dgv.Rows.Add(dt.Rows.Count);
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    for (int k = 0; k < dt.Columns.Count; k++)
                    {
                        dgv.Rows[i].Cells[k].Value = dt.Rows[i][k].ToString();//赋值
                    }
                }
            }
        }
        //datagridview添加行号
        private void dataGridView1_RowStateChanged(object sender, DataGridViewRowStateChangedEventArgs e)
        {
            e.Row.HeaderCell.Value = (e.Row.Index + 1).ToString();
        }
        //解析XML生成DATATABLE
        private List<string> IDList = new List<string>();//用来记录已有的ID,以在修改时判断是否新增
        private DataTable GetXML(string path)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("ID");
            dt.Columns.Add("NAME");
            dt.Columns.Add("SEX");
            dt.Columns.Add("PHONE");
            XmlDocument doc = new XmlDocument();
            doc.Load(path);
            XmlNodeList nod = doc.DocumentElement.ChildNodes;
            foreach (XmlNode peo in nod)
            {
                XmlNodeList pe = peo.ChildNodes;
                DataRow row = dt.NewRow();
                foreach (XmlNode p in pe)
                {
                    if (p.Name == "ID")
                    {
                        row["ID"] = p.InnerText.ToString();
                        IDList.Add(p.InnerText.ToString());//添加ID记录,以在修改时判断是否新增
                    }
                    if (p.Name == "NAME")
                    {
                        row["NAME"] = p.InnerText.ToString();
                    }
                    if (p.Name == "SEX")
                    {
                        row["SEX"] = p.InnerText.ToString();
                    }
                    if (p.Name == "PHONE")
                    {
                        row["PHONE"] = p.InnerText.ToString();
                    }
                }
                dt.Rows.Add(row);
            }
            return dt;
        }
        //修改dgv数据后保存到XML文件
        private int SaveDgv()
        {
            int n = 0;
            for (int i = 0; i < dgvXML.Rows.Count-1; i++)
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(this.txtPath.Text);
                XmlNodeList nod = doc.DocumentElement.ChildNodes;
                string id = dgvXML.Rows[i].Cells[0].Value.ToString();
                if (IDList.Contains(id)) //如果是已有的ID,则修改
                {
                    foreach (XmlNode peo in nod)
                    {
                        if (XmlNode.Equals(peo.SelectSingleNode("ID").InnerText, id))
                        {
                            peo.SelectSingleNode("NAME").InnerText = dgvXML.Rows[i].Cells[1].Value.ToString();//赋值姓名
                            peo.SelectSingleNode("SEX").InnerText = dgvXML.Rows[i].Cells[2].Value.ToString();//赋值性别
                            peo.SelectSingleNode("PHONE").InnerText = dgvXML.Rows[i].Cells[3].Value.ToString();//赋值电话
                            doc.Save(this.txtPath.Text);
                            n++;
                            break;//当找到该ID记录并修改后,跳出循环
                        }
                    }
                }
                else //否则为新增
                {
                    XmlNode root = doc.DocumentElement;
                    XmlElement PERSON = doc.CreateElement("PERSON");
                    XmlElement ID = doc.CreateElement("ID");
                    ID.InnerText = id;//赋值id
                    XmlElement NAME = doc.CreateElement("NAME");
                    NAME.InnerText = dgvXML.Rows[i].Cells[1].Value.ToString();//赋值姓名
                    XmlElement SEX = doc.CreateElement("SEX");
                    SEX.InnerText = dgvXML.Rows[i].Cells[2].Value.ToString();//赋值性别
                    XmlElement PHONE = doc.CreateElement("PHONE");
                    PHONE.InnerText = dgvXML.Rows[i].Cells[3].Value.ToString();//赋值电话
                    PERSON.AppendChild(ID);
                    PERSON.AppendChild(NAME);
                    PERSON.AppendChild(SEX);
                    PERSON.AppendChild(PHONE);
                    root.AppendChild(PERSON);
                    doc.Save(this.txtPath.Text);//保存
                    n++;
                }

            }
            return n;
        }

XML文件:

<?xml version="1.0" standalone="yes"?>

<List>

  <PERSON>

    <ID>001</ID>

    <NAME>测一</NAME>

    <SEX>男男</SEX>

    <PHONE>13543234355</PHONE>

  </PERSON>

  <PERSON>

    <ID>002</ID>

    <NAME>再二</NAME>

    <SEX>女女</SEX>

    <PHONE>13245678903</PHONE>

  </PERSON>

  <PERSON>

    <ID>003</ID>

    <NAME>张三</NAME>

    <SEX>男男</SEX>

    <PHONE>13544678934</PHONE>

  </PERSON>

  <PERSON>

    <ID>005</ID>

    <NAME>王五</NAME>

    <SEX>女女</SEX>

    <PHONE>12345678900</PHONE>

  </PERSON>

</List>

温馨提示:内容为网友见解,仅供参考
第1个回答  2015-04-14
您好,这个源码是我根据网上一个vb.net编辑xml文件的原理用c#重写的。除重用xml文件外.
并未重用任何代码!.
这小段代码,可对xml文件的记录进行删除,修改,或增加新记录。
利用了datagrid控件的sortcommand事件对xml里的记录进行排序。
email:ouyang76.263.net
------------------------------------------
< %@page language="c#" Trace="true"%>
<%@import namespace="System.Data"%>
<%@import namespace="System.IO"%>
<script language="c#" runat="server">
string xmlfile="books2.xml",xpath;
void page_load(Object obj,EventArgs e)
{
xpath=Server.MapPath(xmlfile);
if(!Page.IsPostBack)
{
Dataload("isbn");
}
}

void Dataload(string psort)
{
DataSet ds=new DataSet();
FileStream fs=new FileStream(xpath,FileMode.Open);
ds.ReadXml(fs);

if(ds.Tables.Count==0)
{
Response.Write("xml文件内无记录!!!!");
fs.Close();
Response.End();
}
Trace.Warn("表记录数",Convert.ToString(ds.Tables[0].Rows.Count));

DataRow dr=ds.Tables[0].NewRow();//新建一行
dr["ISBN"] = " Add ISBN";
ds.Tables[0].Rows.InsertAt(dr,0);//插入到第0行位置

Trace.Warn("表数目",Convert.ToString(ds.Tables.Count));//以红字显示调试信息

//grid1.DataSource=ds.Tables[0].DefaultView;
//grid1.DataBind();

DataView dv=new DataView(ds.Tables[0]);
Trace.Warn("字串长度:"+psort,Convert.ToString(psort.Length));//排序字符串的长度
if(psort.Length>0)
dv.Sort=psort;

grid1.DataSource=dv;
grid1.DataBind();
fs.Close();
}

void grid_sort(Object obj,DataGridSortCommandEventArgs e)
{
if(grid1.EditItemIndex==-1)
Dataload(e.SortExpression);
else
Response.Write("正在编辑暂不能排序!!");
}

void grid_edit(Object obj,DataGridCommandEventArgs e)
{
grid1.EditItemIndex=(int)e.Item.ItemIndex;
show_del("hide");
Dataload("");
}

void grid_cancel(Object obj,DataGridCommandEventArgs e)
{
grid1.EditItemIndex=-1;
show_del("show");
Dataload("");
}

void grid_update(Object obj,DataGridCommandEventArgs e)
{
int numcell=e.Item.Cells.Count;//单元格数目(e.Item是当前发生事件的表格行)
int currentrow=e.Item.DataSetIndex;
//int curr2=e.Item.ItemIndex;//与上句等价,可以不带(int)
Trace.Warn("当前更新行号 = ",Convert.ToString(currentrow));
//Trace.Warn("2当前更新行号 = ",Convert.ToString(curr2));

DataSet ds=new DataSet();
ds.ReadXml(xpath);//将xml模式和数据读取到dataSet;
DataRow dr;//表示DataTable中的一行信息.

if(currentrow==0)
dr=ds.Tables[0].NewRow();
else
dr=ds.Tables[0].Rows[e.Item.DataSetIndex - 1];

string[] str={"isbn", "author", "title", "category", "comments"};
int j=-1;
for(int i=2;i<numcell;i++)//跳过1和2column
{
j=j+1;
string ctext;
ctext=((TextBox)e.Item.Cells[i].Controls[0]).Text;

dr[str[j]] = ctext;
Trace.Warn(Convert.ToString(i)+str[j]+":每一行的文本",ctext);
}

if(currentrow==0)
{
Response.Write("加入新记录!!");
ds.Tables[0].Rows.InsertAt(dr,0);
}

ds.WriteXml(xpath);//将表示dataset的xml写入到xml文件中,包括数据和模式.
grid1.EditItemIndex = -1;//无此句仍在编辑界面
show_del("show");
Dataload("");
}

void show_del(string state)
{
string tmp=state;
switch(tmp)
{
case "show":
grid1.Columns[0].Visible = true;
break;
case "hide":
grid1.Columns[0].Visible = false;
break;
default:
grid1.Columns[0].Visible = true;
break;//也要带break
}
}
void initialize(Object obj,DataGridItemEventArgs e)//注意参数与其它函数不同
{
//e.Item.Cells[0].Text="aaaaa";//
if(e.Item.ItemIndex==0)//如果是第一行
{
LinkButton a0=new LinkButton();
a0=(LinkButton)e.Item.Cells[0].Controls[0];

LinkButton a1=new LinkButton();
a1=(LinkButton)e.Item.Cells[1].Controls[0];//在grid内建一个linkbutton控件

if(a0.Text=="删 除")
a0.Text="";
if(a1.Text=="编 辑")
a1.Text="[AddNew]";
}
}

void grid_del(Object obj,DataGridCommandEventArgs e)
{
Response.Write("XX");
Trace.Warn("正要删除",Convert.ToString(e.Item.ItemIndex));//控件中的行数
int curr=e.Item.ItemIndex;
DataSet ds=new DataSet();
ds.ReadXml(xpath);

DataRow dr=ds.Tables[0].Rows[curr-1];//有一行是新加的。
dr.Delete();//找到相应的数据行,将其删除
ds.WriteXml(xpath);

grid1.EditItemIndex = -1;
Dataload("");
}
</script>
<form runat="server">
<asp:datagrid id="grid1" runat="server"
alternatingitemstyle-backcolor="#eeeeee"
headerstyle-backcolor="lightyellow"
font-size="10pt"
allowsorting="true"
onsortcommand="grid_sort"
oneditcommand="grid_edit"
oncancelcommand="grid_cancel"
onupdatecommand="grid_update"
onitemcreated="initialize"
ondeletecommand="grid_del"
bordercolor="#999999"
>
<columns>
<asp:buttoncolumn text="删 除" commandname="delete"/>
<asp:editcommandcolumn buttontype="linkbutton" updatetext="更 新" canceltext="取 消" edittext="编 辑" headertext=""/>
</columns>
</asp:datagrid>
</form>
--------------------------------------------------------------------
xml文件(文件名:books2.xml)
<?xml version="1.0" standalone="yes"?>
<books>
<book>
<isbn>2e2e2we2we2</isbn>
<author>fefdw</author>
<title>2e2eef</title>
<category>324tg</category>
<comments>r3rrgeqw21</comments>
</book>
<book>
<isbn>1234345</isbn>
<author>ssdfdfe</author>
<title>fgregre</title>
<category>r4er43trt</category>
<comments>r3r3redqeq</comments>
</book>
<book>
<isbn>1234345</isbn>
<author>ssdfdfe</author>
<title>fgregre</title>
<category>r4er43trt</category>
<comments>r3r3redqeq</comments>
</book>
<book>
<isbn>0679757651</isbn>
<author>Tom Peters</author>
<title>Circle of Innovation</title>
<category>marketing</category>
<comments>His most recent book is his best by far!</comments>
</book>
<book>
<isbn>0884270610</isbn>
<author>Eli Goldthrait</author>
<title>The Goal</title>
<category>management</category>
<comments>Advocate of Theory of Constraints as applied to managment and optimization.</comments>
</book>
<book>
<isbn>068485600X</isbn>
<author>Jeff Cox, Howard Stevens</author>
<title>Selling the Wheel</title>
<category>management</category>
<comments>Excellent Treatise/Novel on the entire Sales Cycle</comments>
</book>
<book>
<isbn>0672316498</isbn>
<author>Alan Cooper</author>
<title>The Inmates Are Running The Asylum</title>
<category>management</category>
<comments>The father of Visual Basic and creator of the new art of Interaction Design - very valuable in designing websites. Basically the worlds most cutting edge thinker in User Interface design aimed at simplifying software use.</comments>
</book>
</books>本回答被提问者采纳

C#用datagriview控件增加删除行数据,并且更新到xml中,求代码(急...
\/\/选择XML按钮 private void btnXML_Click(object sender, EventArgs e) { DataTable dt = new DataTable(); OpenFileDialog xmlFile = new OpenFileDialog(); xmlFile.Filter = "*.xml|"; xmlFile.Title = "请选择xml文件"; if (xmlFile.ShowDialog() == DialogResult....

C#中 datagriview控件怎么实现累加显示?? 扫一个条码就在datagridview里 ...
int index = this.dataGridView1.Rows.Add();\/\/新建行,然后获得新行的索引this.dataGridView1.Rows[index].Cells[0].Value = Title;this.dataGridView1.Rows[index].Cells[1].Value = DateTime.Now.ToString();this.dataGridView1.Rows[index].Cells[2].Value = Result;this.dataGridView1....

怎么向C#中的datagriview逐条添加数据
row.Cells.Add(c.CellTemplate.Clone() as DataGridViewCell);\/\/给行添加单元格 } row.Cells[0].Value = reader.GetString(0); \/\/给DataGridViewRow添加数据 row.Cells[1].Value = reader.GetString(1); \/\/给DataGridViewRow添加数据 row.Cells[2].Value = reader.GetString(2); \/\/...

C# 如何刷新 父窗口的 datagridview。我做了一个增加窗口,增加成功后关 ...
if (Form01.EditOk){ Edt = Form01.EditValue.ToString();\/\/这里传入Form01中的变量到主窗口。if (更新数据的函数,如果成功则){ 刷新datagriview } else { MessageBox.Show("修改数据失败");} }

c#怎样选择treeview子节点后在datagridview中显示对应的数据?
Nodes获得节点的值,或对应的值,然后把值封装到集合对象。然后循环改集合对象将数据加到datagriview中,或者直接点出datagriview的datasourece将集合赋给datagriview

在C#.NET的gridview和datalist的中怎么样屏蔽按钮的多次点击执行多次的...
DataList.ItemCreated += new DataListItemEventHandler(dl_ItemCreated);加入这个方法:void dl_ItemCreated(object sender, DataListItemEventArgs e){ LinkButton lb = e.Item.FindControl("LinkButton") as LinkButton; \/\/LinkButton 是你嵌套在里面的链接的控件名 if (lb != null) lb.Attributes...

在C#中用Vs2010实现数据的模糊查询(窗体中含有一文本框和两个单选按钮...
数据类型为int。---指的是?slqconnection conn=new sqlconnection("数据库连接字符串");string str="select * from table1 where " ;if(radiobutton1.selected){\/\/学号按钮()str+="学号='"+this.textBox1.text.tostring()+"'";} if(radiobutton2.selected){\/\/姓名按钮 str+="姓名='"+...

相似回答