How to save changes back to XML file from a datasource? - c#

Here is the XML file:
<Test>
<Code Layer='V' Colour='1'/>
<Code Layer='W' Colour='1'/>
<Code Layer='WE' Colour='1'/>
</Test>
My Form (WinForm) has a DataGridView on it and I have bound the view to my XML file:
private void GENIO_Code_Editor_Load(object sender, EventArgs e)
{
DataSet dataSet = new DataSet();
dataSet.ReadXml("d:\\MyFile.xml");
dataGridView.DataSource = dataSet.Tables[0];
}
It works (note that example has more codes in the XML file):
My problem is that, if I type in new values at the bottom (asterix row) these new additions are not getting updated in the XML file.
What step am I missing? Thank you.

The values in the dataset are not saved automatically. To save the dataset use the .WriteXml method.
dataSet.WriteXml("d:\\MyFile.xml");

Related

how to filter a grid based on codtions and than bind the grid using xml

I have one text box and a button and a grid
textbox ID-->Client side---------------->txtFirstName
button Name-->Client side--------------->btnSearch
Grid id-->Client side------------------->gvContactUS
On click of button Search i am trying to search a record which i have entered in textbox whose name is is their in the xml file and will show that in the grid
my xml file is :Contact.xml
<CATALOG>
<CD>
<ID>1</ID>
<HeaderDetailID>1</HeaderDetailID>
<FirstName>Basant</FirstName>
<LastName>Gera</LastName>
<EmployeeID>0012</EmployeeID>
<Department>SD</Department>
<Postion>Programmer</Postion>
<Application>P and L - Joint Cost***BI_AP_KL_COST</Application>
<Filter>Africa_ww_READ</Filter>
<AreaorCountryorStation>India</AreaorCountryorStation>
<NetworkDomain>.Net</NetworkDomain>
<Action>
Modification
</Action>
<NameOfController>Nitin</NameOfController>
</CD>
</CATALOG>
I am trying to filter only 1 record which is their into the grid.
But i am getting the full grid.
Code as follows:
protected void btnSearch_Click(object sender, EventArgs e)
{
string FilepathContact;
string FirstName = txtFirstName.Text;
FilepathContact = Server.MapPath("~/Contact.xml");
DataSet dsdata = new DataSet();
dsdata.ReadXml(FilepathContact);
}
if (dsdata.Tables["CD"].Rows.Count != 0)
{
for (int i = 0; i < dsdata.Tables["CD"].Rows.Count; i++)
{
if (Convert.ToString(dsdata.Tables["CD"].Rows[i]["FirstName"]) == Convert.ToString(FirstName))
{
gvContactUS.DataSource = dsdata;
gvContactUS.DataBind();
}
}
}
}
Now I am getting all the records which is their in my grid.
How do i find the element and search if its their than bind the grid only with that record which is their in data set.
I am using .net Framework 2.0 so LINQ dont work her.

How to display a already defined datatable in datagridview?

I have a regular datatable created, it exports and imports into xml and everything is fine.
To make easy its acess, i created a datagridview, and i'm trying to make the dataatable content available there
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
dataGridView1.DataSource = DataAccess.Instance.tabelaEC0;
}
(i got the table created in a different class so it would be available to all forms)
all i get is a empty gridview
Here is an example of setting a DataSource on DataGridView. DataSet1 is a typed dataset with one table "DataTable1" having one string column:
DataSet1 ds = new DataSet1();
ds.DataTable1.AddDataTable1Row("test");
dataGridView1.DataMember = "DataTable1";
dataGridView1.DataSource = ds;
Alternatively you can bind a table as DataSource:
DataSet1 ds = new DataSet1();
ds.DataTable1.AddDataTable1Row("test");
dataGridView1.DataSource = ds.DataTable1;

Show DataTable in a TreeView control

I have a DataTable TblTreeView which has four columns
ParentID(pk) | ParentName| LeftChildID | RightChildID
and I want to display all data in tree view ;
like so
ParentName
|
|_LeftChildID
|
|_RightChildID
I was using
SqlDataAdapter dataAdapter = new SqlDataAdapter("Select * from tblTreeView", SqlCon);
DataSet dataSet = new DataSet();
dataAdapter.Fill(dataSet);
TreeView1.DataSource = dataSet.Tables[0];
TreeView1.DataBind();
Then an error occurred:- HierarchicalDataBoundControl only accepts data sources that implement IHierarchicalDataSource or IHierarchicalEnumerable.
Please give me the code to do this;
Thank you Sir/Madam
These samples may be a guide
Implementing IHierarchy Support Into Your Custom Collections
A Hierarchical Repeater and Accessories to Match
I see this Article is very great to bind data from Dataset.
Binding the ASP.NET TreeView to a DataSet or an ObjectDataSource
I implemented this code like the following..
private void GenerateCoaTree()
{
DataSet ds = new DataSet();
dcAccountingDataContext dc = new dcAccountingDataContext();
DataTable dt = dc.usp_RPT_ChartOfAccount_Select(null, CompanyID).CopyToDataTable();
ds.Tables.Add(dt);
// The second parmeter for the ID of the element and the third parameter is the ID of the parent element in the tree.
TreeViewCoa.DataSource = new HierarchicalDataSet(ds, "AccountID", "COA_ID");
TreeViewCoa.DataBind();
}
and I invoked this method inside Page_Load page for binding the TreeView control when page loaded for the first time.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
GenerateCoaTree();
}
}
<asp:TreeView ID="TreeViewCoa" runat="server">
<DataBindings>
<asp:TreeNodeBinding DataMember="System.Data.DataRowView"
TextField="COADescription" ValueField="AccountID" />
</DataBindings>
</asp:TreeView>
I hope this will help you solving your issue :).

save new rows in dataset back out to xml

Can't quite figure out what else I need to do to make this work.
I am trying to add more rows to my dataset and datagridview then output either one to an xml
Ideally I want to save the values in dataset then bind datagridview and when closing the form output the dataset out to an xml file. But for some reason this doesn't work. It does update changes to current rows but doesn't add new rows.
public void LoadSongInfo(string filename)
{
TagLib.File tagFile = TagLib.File.Create(filename);
string artist = tagFile.Tag.FirstAlbumArtist;
string album = tagFile.Tag.Album;
string title = tagFile.Tag.Title;
DataRow newtrack = dsStore.Tables["Track"].NewRow();
newtrack["Id"] = "5";
newtrack["Artist"] = artist;
newtrack["Album"] = album;
newtrack["Filepath"] = filename;
newtrack["Title"] = title;
dsStore.Tables["Track"].Rows.Add(newtrack);
dsStore.Tables["Track"].AcceptChanges();
dataGridView1.DataMember = "Track";
dataGridView1.DataSource = dsStore;
}
private void mediaplayer_FormClosing(object sender, FormClosingEventArgs e)
{
string path = "..//..//..//temp.xml";
dataGridView1.EndEdit();
if (dsStore.GetChanges() != null)
{
dsStore.WriteXml(path);
}
}
I have noticed that
dsStore.GetChanges()
returns null unless cell has been edited. So I tried removing that if statement but still nothing.
EDIT: I've tried to write to an empty xml file to see if it writes at least something, and no errors it goes through like everything is ok, then when i open up test2.xml its blank nothing was written. :(
private void mediaplayer_FormClosing(object sender, FormClosingEventArgs e)
{
string path2 = "..//..//..//test2.xml";
dsStore.WriteXml(path2);
}
You have the line:
dsStore.Tables["Track"].AcceptChanges();
This will update the RowState to 'DataRowState.Unchanged' for every row in that table. This is why
dsStore.GetChanges()
is not returning any changes.
Try removing the AcceptChanges() call.
Try removing the
dataGridView1.EndEdit();
this is used if a cell is being edited so the fact that it's only working when you edit a cell could be caused because of that line.
Ok I got this to work..
First mistake what that I was trying to WriteXml in the LoadSong function which can't be done because that function is being called from a ForEach Loop.
I then went to my FormClosing and just did it this way:
private void mediaplayer_FormClosing(object sender, FormClosingEventArgs e)
{
dsStore.WriteXml(path);
}
And last not sure if it's needed but I set my dataset on top like this:
public DataSet dsStore = new DataSet();
added the "public" in case it wasn't keeping the values..Thanks everyone for you help.

LINQ to XML and DataGridView

Hi I’m trying to use a DataGridView for the first time and with LINQ.
Here’s what I’m trying to do:
I want to use it (although it doesn’t have to the DataGridView ) to read and display the contents of an XML file (this bit is working code below) but I want to have an add row button on the form or in the DataGridView that takes the contents of three textboxes and and populates the contents of three columns of the new row. The new row is to be appended to the existing data.
Next I would like to add a Delete button to delete the currently selected row.
And lastly I want a save button that exports the contents of the DataGridView back to an XML file overwriting/updating the existing XML file.
So I stuck at adding the additional data! but as I don't currently have a clue as to the delete or save either I thought I would ask all in one go!!
So this is the code I have to read the xml file:
XDocument xmlDoc = XDocument.Load(#"queues.xml");
var q = from c in xmlDoc.Root.Descendants("Queue")
select new
{
QueueNumber = c.Element("Number").Value,
QueueName = c.Element("Name").Value,
QueuePCC = c.Element("QueueTag").Value
};
dataGridView1.DataSource = q.ToList();
XML document:
<?xml version="1.0" encoding="utf-8" ?>
<Queues>
<Queue>
<Number>
001
</Number>
<Name>
mytest
</Name>
<QueueTag>
xyz
</QueueTag>
</Queue>
<Queue>
<Number>
002
</Number>
<Name>
Adi2
</Name>
<QueueTag>
ABCD
</QueueTag>
</Queue>
</Queues>
ok I have now changed my code to this:
XDocument xmlDoc = XDocument.Load(#"queues.xml");
var q = from c in xmlDoc.Root.Descendants("Queue")
select new Queue
{
Number = c.Element("Number").Value,
Name = c.Element("Name").Value,
QueueTag= c.Element("QueueTag").Value
};
var queryAsList = new BindingList<Queue>(q.ToList());
bindingSource1.DataSource = queryAsList;
dataGridView1.DataSource = bindingSource1;
This allows me to add and delete rows and data from the dataGridView :)
But I can still find no way to writing the data back to XML either from the dataGridView or from the bindingSource1 :(
Any help please?
the bindingSource1.count changes each time I make a change to the data so I think I'm close!
Perhaps you may try working with the xmlDoc saved in the session (thus preserved with the postbacks)... Add the three elements (from the textboxes) to the XmlDoc... And rebind the gridview to the xmlDoc at each postback.
At the end, you could do xmlDoc.save().
For deleting rows, you could use the GridView event, dataGridView1_RowDeleted, to edit the xmlDoc (to remove the node relative to the selected row).
Something like:
protected void ButtonLoadGridView_Click(object sender, EventArgs e)
{
XDocument xmlDoc = XDocument.Load(#"f:\queues.xml");
var q = from c in xmlDoc.Root.Descendants("Queue")
select new
{
QueueNumber = c.Element("Number").Value,
QueueName = c.Element("Name").Value,
QueuePCC = c.Element("QueueTag").Value
};
dataGridView1.DataSource = q.ToList();
Session.Add("xmlDoc",xmlDoc);
}
public void dataGridView1_RowDeleting(Object sender, GridViewDeleteEventArgs e)
{
// get some node information:
int rowIndex = e.RowIndex;
string someNodeInfo = dataGridView1.Rows[rowIndex].Cells[0].Text;
// then edit xml :
XmlDocument xmlDoc = (XmlDocument) Session["xmlDoc"];
xmlDoc.ChildNodes.Item(rowIndex).RemoveAll();
Session.Add("xmlDoc", xmlDoc);
}
protected void ButtonSave_Click(object sender, EventArgs e)
{
XmlDocument xmlDoc = (XmlDocument)Session["xmlDoc"];
xmlDoc.Save(#"f:\queues2.xml");
}

Categories