How to delete specific DataRow in DataSet?
Hey guys, I am trying to delete a specific xml datarow with a specific value but it's not working out for me. Here's my code and the error I receive:
DataSet ds = new DataSet();
StreamReader sr = new StreamReader(pathToFile + "AlertSettings.xml");
ds.ReadXml(sr);
sr.Close();
DataRow rowToDelete = ds.Tables[0].NewRow();
rowToDelete["PublicationToAlert"] = publication;
if (ds.Tables[0].Rows.Contains(rowToDelete))
{
ds.Tables[0].Rows.Remove(rowToDelete);
ds.AcceptChanges();
ds.WriteXml(pathToFile + "AlertSettings.xml", XmlWriteMode.IgnoreSchema);
}
Here is the error message: "The given DataRow is not in the current DataRowCollection"
I want to delete the row where it's value is equal to the "publication" parameter's value that is being passed in. (i.e. rowToDelete["PublicationToAlert"] = publication;)
The remove command breaks and so does this line of code:
if (ds.Tables[0].Rows.Contains(rowToDelete))
I get the following error with the above line: "Table doesn't have a primary key"
Any help would be greatly appreciated. Thanks guys.
Andrew FurtadoPosted Nov 28, 2006, 2:58 PM
Heh... You can determine existing of value to be deleted by simple construction:
bool exists = (dr.Length > 0); // insert this after calling Select method
ChrisPosted Nov 28, 2006, 2:43 PM
Andrew FurtadoPosted Nov 28, 2006, 2:10 PM
Really I don't know why your XML is not shown. Possible you try paste XML in HTML Source Mode (in this case you can change the mode to normal by clicking the button with "<>" symbol).
As another solution I suggest to send to me your XML by e-mail. :)
ChrisPosted Nov 28, 2006, 1:55 PM
string criteria = "PublicationToAlert = " + publication; foreach (DataRow r in ds.Tables[0].Select(criteria)) r.Delete(); ds.AcceptChanges(); ds.WriteXml(pathToFile + "AlertSettings.xml", XmlWriteMode.IgnoreSchema);Why is my xml not posting??Andrew FurtadoPosted Nov 28, 2006, 1:53 PM
ChrisPosted Nov 28, 2006, 1:33 PM
ChrisPosted Nov 28, 2006, 1:30 PM
BriefChart
Schedule
test
I want the row that has the value "test" deleted, or any value dynamically for that matter. Thanks!!!Andrew FurtadoPosted Nov 28, 2006, 12:26 PM
Should be something like this: (I didn't check this code. Take it as an idea only.)
DataSet ds = new DataSet();
StreamReader sr = new StreamReader(pathToFile + "AlertSettings.xml");
ds.ReadXml(sr);
sr.Close();
// DataRow rowToDelete = ds.Tables[0].NewRow();
// rowToDelete["PublicationToAlert"] = publication;
// if (ds.Tables[0].Rows.Contains(rowToDelete))
// {
// ds.Tables[0].Rows.Remove(rowToDelete);
// ds.AcceptChanges();
// ds.WriteXml(pathToFile + "AlertSettings.xml", XmlWriteMode.IgnoreSchema);
// }
string criteria = "PublicationToAlert = " + publication;
foreach (DataRow r in ds.Table[0].Select(criteria)) r.Delete();
ds.AcceptChanges();
...