How to get a value from a column in a DataView? - c#

I have a dataview defined as:
DataView dvPricing = historicalPricing.GetAuctionData().DefaultView;
This is what I have tried, but it returns the name, not the value in the column:
dvPricing.ToTable().Columns["GrossPerPop"].ToString();

You need to specify the row for which you want to get the value. I would probably be more along the lines of table.Rows[index]["GrossPerPop"].ToString()

You need to use a DataRow to get a value; values exist in the data, not the column headers. In LINQ, there is an extension method that might help:
string val = table.Rows[rowIndex].Field<string>("GrossPerPop");
or without LINQ:
string val = (string)table.Rows[rowIndex]["GrossPerPop"];
(assuming the data is a string... if not, use ToString())
If you have a DataView rather than a DataTable, then the same works with a DataRowView:
string val = (string)view[rowIndex]["GrossPerPop"];

#Marc Gravell ....
Your answer actually has the answer of this question.
You can access the data from data view as below
string val = (string)DataView[RowIndex][column index or column name in double quotes] ;
// or
string val = DataView[RowIndex][column index or column name in double quotes].toString();
// (I didn't want to opt for boxing / unboxing) Correct me if I have misunderstood.

for anyone in vb.NET:
Dim dv As DataView = yourDatatable.DefaultView
dv.RowFilter ="query " 'ex: "parentid = 1 "
for a in dv
dim str = a("YourColumName") 'for retrive data
next

Related

Getting a Value in the First index of a TableAdapter in C#

Am trying to get a a Zero indexed Value from a column in the TableAdpter but it has refused , how can i retrieve a value in the Column index Zero , below is my code :
LoginTableAdapter l = new LoginTableAdapter();
string res = l.GetData("mueat", "1234").Rows[0].ToString();
And my table which is attached to the TableAdapter is as below , it's one column and i want to get the value t which is in a Zero index in the column access:
If we assume l.GetData("mueat", "1234") returns a DataTable, like so:
DataTable table = l.GetData("mueat", "1234"); // the dataTable
then this:
DataRow row = table.Rows[0]; // first row;
will only give you the first row out of the DataRowCollection's indexer
As we can see on the DataRow type, it has an indexer as well, giving access to the columns in the DataRow instance.
object columnValue = row[0]; // first column
You can now cast the object value to the correct type or call ToString on it to convert it to its string representation.
Putting this all back together in your compact one-liner you will get:
string res = l.GetData("mueat", "1234").Rows[0][0].ToString();

Dataview Rowfilter

I have a textbox and a button. What i am attempting to do is filter a gridview with the data that has been searched for. The two fields im searching for are customerID and CustomerName.
My code:
Dim GetAllCusts As New BusinessLayer.Customer
Dim dt As DataTable = GetAllCusts.GetCustomers
Dim dv As New DataView(dt)
dv.RowFilter = String.Format("CustomerID='{0}' Or CustomerName='{0}'", SearchTextbox.Text)
gridview1.DataSource = dv
gridview1.DataBind()
When searching for a customer id everything works. When searching for a customer name i get "Cannot perform '=' operation on System.Int32 and System.String.".
I tried to CONVERT(CustomerName, System.String) but that didnt resolve however i think this was leading me away from the initial problem as i started to guess around.
I would like to have one textbox to search for a customer id and customer name. What is wrong with the RowFilter and how could it be resolved?
Thanks
You have a conceptual problem. Or you search for a number or you search for a string.
I think you should change your code in this way
Dim custID as Integer
if Int32.TryParse(SearchTextbox.Text, custID) Then
' CustomerID is a numeric field - no need to use single quotes'
dv.RowFilter = String.Format("CustomerID={0}", custID)
else
' CustomerName is a string. Use single quotes and double the '
' possible single quotes inside the search box'
dv.RowFilter = String.Format("CustomerName='{0}'", SearchTextbox.Text.Replace("'", "''")
End If
gridview1.DataSource = dv
I guess CutomerId is a integer field and when you try to search for a Name which is a string field you are trying to search an integer field with a string value.

C# Datatable woes

I have a database command that populates a DataTable I want to get the value of an entry in the Datatable, based on, A: The numeral index of the row, and b, the string name of the column. That's all I want, how is that possible?
yourDatatable.Rows[rowIndex]["columnName"] should work
myTbl.Rows[0]["b"];
A is not a row index.
DataTable dt = GetData();
var result = dt.Rows[RowIndex]["MyColumnName"];
The RowIndex is an indexed property of the datatable which returns a DataRow. "MyColumnName" is an indexed property of the DataRow, returning the value as an object.

Convert datarow to int

I have a datarow, but how can i convert it to an int ?
I tried this, but it doesn't work.
dsMovie = (DataSet)wsMovie.getKlantId();
tabel = dsMovie.Tables["tbl_klanten"];
eersteRij = tabel.Rows[0];
(Int32.Parse(eersteRij.ToString())
A DataRow is an object; it is not an integer. A DataRow contains one or more columns of data. You can index into the DataRow to access the values of these coulmns.
If table tbl_klanten contains one column, and that column is an integer, you can do the following:
var myInt = (int)eersteRij[0];
if the column is a string containing the value of an integer,
var myInt = int.Parse(eersteRij[0]);
If the column is named klant_id...
var myInt = (int)eersteRij["klant_id"];
if the column is a string containing the value of an integer,
var myInt = int.Parse(eersteRij["klant_id"]);
Simply use the Field method:
int result = row.Field<int>("ColName");
The Field method also supports nullable types:
The Field method provides support for accessing columns as nullable
types. If the underlying value in the DataSet is Value, the returned
nullable type will have a value of null.
And please notice:
The Field method does not perform type conversions. If type conversion is required, you should first obtain the column value by using the Field method. The column value should then be converted to another type.
Because even at that level of hierarchy you still have a DataRow and you can't convert a DataRow to int.. a value could be converted though.
And why are you converting whole DataRow to int.. usually you would like to get a value in a cell at a row so try, Somthing like this:
int value = (int)eersteRij.Items[0];
where 0 can be replaced by the cell position(int) or Column name(string)
You'll need to know which index the object you want is on, and cast that to an int, e.g.:
int value = (int)eersteRij[0];
DataSet dataSet = getDataFromDatabase();
DataRow tableRow = dataSet.Tables[0].Rows[0];
int valueAsInteger = Convert.ToInt32(tableRow["COLUMN_NAME"]);
I tend to use IndexOf() when looping thru the dataTable.
foreach (DataRow row in DataTable.table.Rows)
{
int index = dataTable.Rows.IndexOf(row);
}

extract data from a dataset

I have a dataset that gets populated from a stored proc in sql server. I have a column that has lets say has a set of values. I do not know what those values are. All I know is that they of the type "string". I want to extract all the distinct values from that column.
You can use a DataView and set its RowFilter to the desired condition:
var view = new DataView(dataset.Tables["Table"]);
view.RowFilter = "Column = 42";
UPDATE: based on your updated question, you can use LINQ:
var table = dataset.Tables["Table"].AsEnumerable();
var distinctValuesForColumn =
table.Select(row => (string)row["Column"]).Distinct();
You can simply use Select method of the DataTable :
DataRow[] extractedRows =
yourDataSet.Tables["YourTableName"].Select("YourColumnName = 123");
You can also use Linq to query your datatables. Here is a link to some examples on the MS site - http://msdn.microsoft.com/en-us/vbasic/bb688086.aspx
I hope below statement will serve your purpose
ds.Tables["TableName"].DefaultView.ToTable( true, "columnName"); //For Dataset (true means distinct)
OR
`ds.Tables[0].DefaultView.ToTable( true, "columnName");
//For Dataset where tableindex is 0
OR
dt.DefaultView.ToTable( true, "columnName"); //For Datatable
//Syntax is like Datatable.DefaultView.ToTable( Distinct true/false, “ColumnName”);
MSDN : http://msdn.microsoft.com/en-us/library/wec2b2e6.aspx

Categories