I am using typed datasets with datagrids. When I delete a row I use the dataset.HasChanges filter and get changes as follows.
dtDel = (Database1DataSet1.product_skuDataTable)database1DataSet1.product_sku.GetChanges(DataRowState.Deleted);
I am trying to get values(Product Names) from deleted rows as follows.
private string getProdNames(DataTable dtDel)
{
string prodNames = "";
var q = dtDel.AsEnumerable().Select(x => x.Field<string>("ProductName"));
foreach (string p in q)
{
prodNames += p + "\n";
}
return prodNames;
}
But I am getting the following error.
Deleted row information cannot be accessed through the row.
Thanks
Found the answer here and here
The linq query will work like this
var q = dt.AsEnumerable().Select(x => x.Field<string>(colName, DataRowVersion.Original));
Related
I'm trying to delete multi rows from data grid view in c#
I use xml file as a database.
Here is my code; when I trying to delete in the data grid view, they are deleted correctly, but in the XML file, just the last selected row is deleted, and the sequence row after it.
var selectedRows = CustomersInformation.SelectedRows
.OfType<DataGridViewRow>()
.Where(row => !row.IsNewRow)
.ToArray();
foreach (var row in selectedRows)
{
XDocument Customersdocument = XDocument.Load(#"customers.xml");
var DeleteQuery = Customersdocument.Descendants("Customer")
.Where(del => del.Element("PhoneNumber").Value ==
CustomersInformation.CurrentRow.Cells[1].Value.ToString());
DeleteQuery.Remove();
Customersdocument.Save(#"customers.xml");
CustomersInformation.Rows.Remove(row);
CustomersInformation.ClearSelection();
}
My XML file looks like this but with more customers
<Customers>
<Customer>
<Name>sara</Name>
<PhoneNumber>7176665</PhoneNumber>
<BirthDate>12/28/2000</BirthDate>
<ExpireDate>2023-03-28T09:15:27.8040881+03:00</ExpireDate>
<PackageId>1</PackageId>
<Balance>8</Balance>
</Customer>
</Customers>
The main problem is this line:
CustomersInformation.CurrentRow.Cells[1].Value.ToString());
The keyword:
...CurrentRow...
acts differently than what you're trying to loop through all the rows in datagridview.
you're trying to do a "foreach" loop, but getting the values from "currentrow".
if you performs a
CustomersInformation.ClearSelection();
The "currentrow" will become "null".
So, u can do this, load the xml first, before the loop:
XDocument Customersdocument = XDocument.Load(#"customers.xml");
foreach (var row in selectedRows)
{
// remove row
}
// save the file after the loop finished
Customersdocument.Save(#"customers.xml");
in the loop:
foreach (var row in selectedRows)
{
// get da phoneNumber from foreach row, not currentrow
var phoneNumber = row.Cells[1].Value.ToString();
// not from currentrow
//var phoneNumber = CurrentRow.Cells[1].Value.ToString();
// generate delete query
var DeleteQuery = Customersdocument.Descendants("Customer")
.Where(del => del.Element("PhoneNumber").Value == phoneNumber);
// do remove
DeleteQuery.Remove();
// remove from teh datagridview
CustomersInformation.Rows.Remove(row);
}
According to my understanding, you should try saving CustomersDocument after the end of the for loop. If the problem is not resolved, try debugging the entire process to determine the exact error.
You can do the following :
XDocument doc = XDocument.Load("customers.xml");
var q = from node in doc.Descendants("Customer")
let attr = node.Attribute("PhoneNumber")
where //your condition here with attr.Value
select node;
q.ToList().ForEach(x => x.Remove());
doc.Save("customers.xml");
// Appetizers Filter
var Appetizers =
from a in this.restaurantMenuDataSet.Menu
where a.Category == "Appetizer"
select a;
foreach (var a in Appetizers) AppCombo.Items.Add(a.ItemName);
So with this I get appetizers from an access database, but I also want to display its price along side it in ComboList. So basically I want the list to show "Nachos $5.95"
Database:
ComboList:
You can use String.Format to combine ItemName and Price in order to display in combobox:
foreach (var a in Appetizers)
{
var displayName = String.Format("{0} {1}", a.ItemName,a.Price);
AppCombo.Items.Add(displayName);
}
I have a CheckedListBox (winforms) with data that is bounded to a datatable:
clbCustomer.DataSource = ds.Tables["Default"];
clbCustomer.DisplayMember = "desc";
clbCustomer.ValueMember = "customerId";
Now I would like to search the checkedlistbox for a particular customer id and then select that row. I can do this with a foreach statement as follows:
// Find the index
int index = 0;
foreach (DataRowView item in clbCustomer.Items)
{
int cusId = Convert.ToInt32(item["customerId"]);
if (cusId == 255)
{
break;
}
index++;
}
// Select the customer
clbCustomer.SetItemChecked(index, true);
However, it seems very bulky to do it this way. I am attempting to convert the above code into linq but have not been able to accomplish it. Here is what I have so far:
// Find the index (not working)
int index = clbCustomer.Items.Cast<DataRowView>().Where(x => x["customerId"] == 255);
// Select the customer
clbCustomer.SetItemChecked(index, true);
But not sure how to extract the index of that customer id using linq. Any help would be appreciated. Thanks.
Solution provided by Keithin8a below:
var item = clbCustomer.Items.Cast<DataRowView>().Where(x => Convert.ToInt32(x["customerId"]) == 255).FirstOrDefault();
int index = clbCustomer.Items.IndexOf(item);
Linq statements like that return a collection as mentioned in the comments. If you were to use
var item = clbCustomer.Items.Cast<DataRowView>().Where(x => Convert.ToInt32(x["customerId"]) == 255).FirstOrDefault()
That would get you your a single item instead of a collection. You can then get the index of this item by calling
int index = clbCustomer.Items.IndexOf(item);
That should get you what you want.
I'm having some difficulties using a lambda expression to parse an html table.
var cells = htmlDoc.DocumentNode
.SelectNodes("//table[#class='data stats']/tbody/tr")
.Select(node => new { playerRank = node.InnerText.Trim()})
.ToList();
foreach (var cell in cells)
{
Console.WriteLine("Rank: " + cell.playerRank);
Console.WriteLine();
}
I'd like to continue to use the syntax as
.Select(node => new { playerRank = node.InnerText.Trim()
but for the other categories of the table such as player name, team, position etc. I'm using Xpath, so I am unsure if its correct.
I'm having an issue finding out how to extract the link + player name from:
Steven Stamkos
The Xpath for it is:
//*[#id="fullPage"]/div[3]/table/tbody/tr[1]/td[2]/a
Can anyone help out?
EDIT* added HTML page.
http://www.nhl.com/ice/playerstats.htm?navid=nav-sts-indiv#
This should get you started:
var result = (from row in doc.DocumentNode.SelectNodes("//table[#class='data stats']/tbody/tr")
select new
{
PlayerName = row.ChildNodes[1].InnerText.Trim(),
Team = row.ChildNodes[2].InnerText.Trim(),
Position = row.ChildNodes[3].InnerText.Trim()
}).ToList();
The ChildNodes property contains all the cells per row. The index with determine which cell you get.
To get the url from the anchor tag contained in the player name cell:
var result = (from row in doc.DocumentNode.SelectNodes("//table[#class='data stats']/tbody/tr")
select new
{
PlayerName = row.ChildNodes[1].InnerText.Trim(),
PlayerUrl = row.ChildNodes[1].ChildNodes[0].Attributes["href"].Value,
Team = row.ChildNodes[2].InnerText.Trim(),
Position = row.ChildNodes[3].InnerText.Trim()
}).ToList();
The Attributes collection is a list of the attributes in an HTML element. We are simply grabbing the value of href.
I am currently using one button for inserting/updating content within a table. It then takes the uploaded CSV and inserts or updates it into a data table depending on whether the row exists or not.
Here is the code fired after the button's OnClick:
if (ExcelDDL.SelectedValue == "Time Points" && fileName == "TimePoints.csv")
{
var GetTPoints = (SEPTA_DS.TimePointsTBLDataTable)tpta.GetDataByCategory(CategoryDDL.SelectedItem.ToString());
//Loop through each row and insert into database
int i = 0;
foreach (DataRow row in TempRouteDataTable.Rows)
{
//Gather column headers
var category = Convert.ToString(CategoryDDL.SelectedItem);
var agency = Convert.ToString(row["Agency"]);
if (agency == null || agency == "")
{
//If row is empty skip it entirely
goto skipped;
}
var route = Convert.ToString(row["Route"]);
var GetRShortName = (SEPTA_DS.RoutesTBLDataTable)rta.GetDataByRouteID(route);
var newRoute = "";
if (GetRShortName.Rows.Count > 0)
{
newRoute = Convert.ToString(GetRShortName.Rows[0]["route_short_name"]);
}
var direction = Convert.ToString(row["Direction"]);
var serviceKey = Convert.ToString(row["Service Key"]);
var language = Convert.ToString(row["Language"]);
var stopID = Convert.ToString(row["Stop ID"]);
var stopName = Convert.ToString(row["Stop Name"]);
if (stopName.Contains("accessible"))
{
string[] noHTML = stopName.Split('>');
int insertH = Convert.ToInt32(hta.InsertHandicapRow(newRoute,noHTML[2]));
}
var sequence = Convert.ToString(row["Sequence"]);
var origID = -1;
if (GetTPoints.Rows.Count > 0)
{
origID = Convert.ToInt32(GetTPoints.Rows[i]["TPointsID"]);
var GetID = (SEPTA_DS.TimePointsTBLDataTable)tpta.GetDataByID(origID);
if (GetID.Rows.Count < 1)
{
origID = -1;
}
}
if (origID == -1)
{
int insertData = Convert.ToInt32(tpta.InsertTimePoints(category, agency, newRoute, direction, serviceKey, language, stopID, stopName, sequence));
}
else
{
int updateData = Convert.ToInt32(tpta.UpdateTimePoints(category, agency, newRoute, direction, serviceKey, language, stopID, stopName, sequence, origID));
}
skipped:
i++;
}
}
You can see how I check whether to insert or update around the bottom. I am using this method across other sections of this program and it works just fine. But in this case it is distorting my datatable immensely and I can't figure out why.
This is the bottom part of my table after inserting [no items currently within the database]:
This is the table after reuploading the CSV with data already existing within the table:
I am also getting this error when updating There is no row at position 2230.
What is going wrong in the code to cause this huge shift? I am just checking to see if the ID exists and if it does update rather than insert.
Also the reason i am using goto is because there are blank rows in the document that need to be skipped.
Is your TPointsID column, a auto-generated number? If so, since you are skipping the empty row, some referential integrity problem might be occuring,because of empty data in the skipped rows in the database.
From the error : There is no row at position 2230 , it is also understood that, because of the skipping you might be trying to access some non existent row in the datatable.
Also, if possible consider using the ADO.NET DataAdapter which has got the CRUD operation capability. You can find more about it at : http://support.microsoft.com/kb/308507