Thursday, March 29, 2012

single value from dataSet

How do you get a single value out of a data set/data table? This will be done multiple times in a loop and I'd rather work on the dataSet. I'm not just grabbing a single value one time(I know I should grab directly from db for this).

ThanksHi,
Having DataSet custDS you will have to do something like this:


foreach (DataRow custRow in custDS.Tables["Customers"].Rows)
{
Console.WriteLine("Customer ID: " + custRow["CustomerID"]);
}

Consider to use DataReader instead of DataSet if you are not caching data.
Thanks, but I know how to loop through all of the records in a data table. What I'm trying to do is target a specific field in the table and grab the data. Going against a db you would write an sql query like, "select phone_num from clients where last_name like 'whatever'.
How do I query a dataSet or dataTable like this? I know that there a couple of commands like datatable.find() and datatable.select() but I can't get them to work for me.
OK,
Now I understand your question. You have 2 options:
1. Use XPath with XML representation of DataSet

DataSet myDataSet = new DataSet("CustomerOrders");
// Fill DataSet here ...

XmlDataDocument xmlDoc = new XmlDataDocument(myDataSet);
XmlNodeList nodeList = xmlDoc.DocumentElement.SelectNodes("descendant::Customers[*/OrderDetails/ProductID=43]");
DataRow myRow = xmlDoc.GetRowFromElement((XmlElement)myNode);
if (myRow != null)
Console.WriteLine(myRow[0]);


2. Use DataView Find method

DataView custView = new DataView(custDS.Tables["Customers"], "",
"CompanyName", DataViewRowState.CurrentRows);

int rowIndex = custView.Find("The Cracker Box");

if (rowIndex == -1)
Console.WriteLine("No match found.");
else
Console.WriteLine("{0}, {1}",
custView[rowIndex]["CustomerID"].ToString(),
custView[rowIndex]["CompanyName"].ToString());

Samples from MSDN

0 comments:

Post a Comment