Getting Value from DataView C# - c#

How to find a value of some column from DataView.CurrentItem.

As Paul pointed out in his comment, there is no CurrentItem member in the DataView class.
If you know the index of the item, you can access a column by its name as shown below :
string name = dataView[index]["Name"] as string;
Similarly, if you have an instance of a DataRowView (a view of a DataRow), you can do that :
string name = dataRowView["Name"] as string;
EDIT: I just noticed the WPF tag on your question... perhaps you're talking about a CollectionView, not DataView ?
CollectionView doesn't have "columns" per se, but it can be represented in a GridView or DataGrid (which both have columns). It's just a view over a collection of objects. To access a specific field or property of the current object, there are two main options :
if you statically know the actual type of the collection items : cast the CurrentItem to that type, and directly access the members you need
if you don't know the type, you can use reflection on the CurrentItem to access its properties or fields by name

Related

Getting values from gridView cell C#

I want to get the data from a cell from a selected row, in a gridView, and bring it into another form, inside a textEdit that then edit the row of the selected cell, the problem is that when using
var cacca = this.gridView.getFocusedRow() as PartnersMissing;
MessageBox.show(cacca.toString())
the messageBox writes Test01.parnersMissing, where Test01 is the name of the project and I really don't know why PartnersMissing is there. What is wrong in this code?
The datagrid has data from an sql database and it is made with DevExpress.
Please don't mind the names for the variables if you know italian, I was in a hurry :D
The current row can be obtained using the GridView's
GetFocusedRow method. This method returns an object whose actual
type is determined according to the data source.
If you are binding it with a List<PartnersMissing> objects then you are getting correct value from the GetFocusedRow method. If you want to access the property of the current row object then you can simply do it.
for example: PartnersMissing has property ABC then you can access as below:
var cacca = this.gridView.getFocusedRow() as PartnersMissing;
MessageBox.show(cacca.ABC)
ToString() method returns the type of the object not any property value. you just printing type of the object rather than accessing property of object.
As Dimitry Says, You can also access particular column value or row' PartnersMissing object property using the GetFocusedRowCellValue(String) Method.
As far as I can see from your code, the result is expected because the cacca.toString() expression return the type name for those types, which do not override the standard object.ToString method.
To show something helpful, you should either to override this method
class PartnersMissing {
public string Name { get; set; }
public override string ToString(){
return Name;
}
}
or to obtain the specific values from your object's fields:
MessageBox.Show(cacca.Name);
You can also to obtain the object's fields value directly from the gridView:
string name = gridView.GetFocusedRowCellValue("Name");

How to get the selected object from the DataGridView?

I have a System.Windows.Forms.DataGridView to show the objects of my type IECInstance.
I'm building a DataTable and fill the table with my objects and set the DataTable as DataSource of my DataGridView. So my DataGridView is showing my objects correctly.
My problem is now to get the objects when i select the row(s).
My first attempt was to use this:
IECInstance theObjectIWant = dataGridView.SelectedRows[0].DataBoundItem as IECInstance.
But DataBountItem returns a DataRowView.
So i found many questions for the issue here on SO and some suggested to use this:
var drv = dataGridView1.SelectedRows[0].DataBoundItem as DataRowView;
var row = drv.Row as DataRow;
var val = row[X] as MyType;
But as far i can see, row[X] is a access to the cell (column), so it does not match to my problem.
When i'm using a List<IECInstances> as DataSource instead of the DataTable, the property DataBoundItem returns the proper object. But actually i don't want to set the DataSource as a List.
To make sure: When i talk about objects i mean my business object of the type IECInstace.
In my first comments I had assumed that the Objects are in fact contained in the Cells' Values. In that case the Cells show whatever the object class's ToString() methods returns. The name 'Value' is a little misleading here as it can hold any object and has nothing to do with value vs reference types.
But in our chat we have established that you create a DataTable and fill it by Linq'ing the objects' properties into it as strings.
So the DataTable as well as the bound DataGridView contain only strings without any reference back to the objects.
To solve the problem you have to include a reference to the original object instances somehow.
One way is to add a Column to the DataTable to hold the reference, maybe like this:
dataGridView1.Columns.Add("hIECInstance", typeof(IECInstance ));
and fill it with the object references, either by including it in the Linq result set or by including it in the list of columns of your Add() command or by setting it separately.
To hide the reference you can set the column in the DGV to be invisible..
dataGridView1.Columns["hIECInstance"].Visible = false;
..and to access the object you cast the Value to your object class:
IECInstance theObject =
dataGridView1.SelectedRows[0].Cells["hIECInstance"].Value as IECInstance;
Another way to display object Properties as columns in a DataGridView is to put them into a List<T>, here a List<IECInstance >.
When you do that you can set the DGV's DataSource to this list
In such a solution the row is directly associated with the source object and you can refer to it on the row level like this:
IECInstance theObject =
dataGridView1.SelectedRows[0].DataBoundItem as IECInstance;
You may want to insert one or two further levels of dataBinding by including BindingList and/or a BindingSource thus adding functionality to the binding .

binding a set of datarows to datagridview

I have tried the following code, but nothing is displayed in datagridview.
Any Suggestions?
string strFilterOption = "dtcolnPurchaseProductExpProductNo=270";
dgvProductExp.DataSource = dtPurchaseProductExp.Select(strFilterOption);
From MSDN
The DataGridView class supports the standard Windows Forms
data-binding model. This means the data source can be of any type that
implements one of the following interfaces:
The IList interface, including one-dimensional arrays.
The IListSource interface, such as
the DataTable and DataSet classes.
The IBindingList interface, such as
the BindingList class.
The IBindingListView interface, such as the
BindingSource class.
Due to the default behavior for databinding with array, you can't set, for the DataSource property, the array of Datarows that the Datatable.Select method will return. From this post:
The primary one is that the object implements IList or is a
1-Dimensional Array. The thing is, an array has a default behavior
for databinding - Reflection. The object type within the array is
reflected to discover its public properties which are not indexed and
with value types that can be represented in the grid. These
properties are then used as the Fields when the databinding occurs.
Since the data type in your array is DataRow, there are six public
properties: HasErrors, Item, ItemArray, RowError, RowState, and
Table. But Item is an indexed property and ItemArray is of type
Object(), which can't be displayed in a gridview, so these two
properties are ignored and the other four are shown in the grid.
So another way would consist to create a new DataTable, using Clone method in order to get the schema from the DataTable source, and populate the new DataTable with the array of DataRows.
string strFilterOption = "dtcolnPurchaseProductExpProductNo=270";
DataTable cloneTable;
cloneTable = dtPurchaseProductExp.Clone();
foreach (DataRow row in dtPurchaseProductExp.Select(strFilterOption))
{
cloneTable.ImportRow(row);
}
dgvProductExp.DataSource = cloneTable;
Or, you can also do your binding through a BindingSource object and use its Filter property.
Have you test dgvProductExp.DataSource.Tables(0).Rows.Count ? .. if it show 0 that's why ..
Or are you sure it's not
string strFilterOption = "dtcolnPurchaseProductExpProductNo='270'"; ?
In case if someone experiencing a similar issue, the easiest way will be to convert the data row array back to datatable and then setting the grid view data source.
dgvProductExp.DataSource = dtPurchaseProductExp.Select(strFilterOption).CopyToDataTable();

Convert to list a object with anonymous type

I need convert to list a object with anonymous type because when i databind the gridview i get
"The data source does not support server-side data paging"
or How i can solve this?
object o = HttpRuntime.Cache[key];
if(o is ICollection)
{
//Sort Object
o = ((IQueryable)this.DataSource).AsQueryable().OrderBy(SortExpresion);
DataSource = o;
DataBind();
}
data returned from cache are ok, the problem is that i extended the gridview control and the data type of datasource is always different, and i need sort this anonymous data stored in cache and use in the gridview
Reason is IQueryable does not support paging. You need to convert it to a more concrete type like List<T> or as REA_ANDREW suggested, PagedDataSource.
Example:
o = ((IQueryable)this.DataSource).AsQueryable().OrderBy(SortExpresion).ToList();
Set the datasource of a PagedDataSource class and then assign this object as the datasource of your gridview. Otherwise, create an object datasource and bind that to your gridview.
Andrew

DataGridView - setting object's displayed value in a column

I bind some collection to a DataGridView. Collection contains KeyValuePair objects where key is a string and value is an object of my class Field. DataGridView displays two columns - one containing the key and the other one containing the value. The value (Field object) is displayed with its ToString() method. But I would like it to be displayed using its Name property. The problem is the column contains no DisplayMember property.
How can i do it?
Edit: I know I could override ToString() to return the name of the object but I don't want to do that.
DataGridView (in common with most direct list-based bindings) can only bind to immediate properties of the row item. You could perhaps create a facade object for this? i.e. a class that accepts the instance and returns the name as a direct property:
public string Name {
get {return innerObject.Name;}
set {innerObject.Name = value;}
}
// snipped: other properties - Key etc
Alternatively, you could project into a new object? For example, data-bindings work (read-only, at least) with anonymous types pretty well:
grid.DataSource = originalData.Select(x=>
new {x.Key, Name = x.Field.Name}).ToList();
Finally, you can hack around in ComponentModel to flatten the model at runtime, but it really isn't worth it just for this.
You could put the DataGridView into virtual mode (view.VirtualMode = true), and handle the CellValueNeeded (and possibly the CellValuePushed) events to access the "Name" property. This would avoid creating lots of wrapper objects, but does make the code somewhat less elegant.

Categories

Resources