I want to get selected DataGrid values.
The following codes work correctly, but when the number of rows selected exceeds 10 items, it encounters an error.
error message: "Object reference not set to an instance of an object"
please Help Me.
for (int i = 0; i < MyGrid.SelectedItems.Count; i++)
{
var item = MyGrid.SelectedItems[i];
if (item == null) { return; }
string Name = (MyGrid.Columns[1].GetCellContent(item) as TextBlock).Text;
MessageBox.Show(Name);
}
The following codes work correctly, but when the number of rows selected exceeds 10 items, it encounters an error ...
That's because the visual containers for the items that you don't currently see on the screen have been virtualized away for performance reasons.
What you should do is to cast SelectedItems[i] to whatever your data object type is and then access the property of this object:
for (int i = 0; i < MyGrid.SelectedItems.Count; i++)
{
var item = MyGrid.SelectedItems[i] as YourClass;
if (item == null) { return; }
string name = YourClass.Name;
MessageBox.Show(name);
}
YourClass refers to the type of the items in the DataGrid's ItemsSource:
dataGrid.ItemsSource = new List<YourClass>() { ... };
Related
i need to get selected value of RepositoryItemRadioGroup
how can i get it ??
for (int i = 0; i < gridView1.RowCount; i++)
{
int rowHandle = gridView1.GetVisibleRowHandle(i);
QuestionsAndAnswers row = (QuestionsAndAnswers)((GridView)gridControl1.MainView).GetRow(rowHandle);
// row.RadioGroup> represent RepositoryItemRadioGroup
//i need to get selected value in row.radiongroup
}
It is not quite clear to me why you need to get access to the RadioGroup directly. If you have bound your GridView to the collection of the QuestionsAndAnswers objects you should not iterate GridView rows itself due to the fact that all the values are already mapped onto the QuestionsAndAnswers properties in a two-way manner. Thus iterate your QuestionsAndAnswers collection directly:
List<QuestionsAndAnswers> qaList = new List<QuestionsAndAnswers> {
new QuestionsAndAnswers(){ Question ="How are you?" }
}
// data binding
gridControl1.DataSource = qaList;
...
void getAnswersBtn_Click(object sender, EventArgs e) {
foreach (QuestionsAndAnswers qa in qaList){
var answer = qa.Answer;
// do something
}
}
If you are bound the GridView in another manner, please, update your question with the detailed description:
- how you bind the GridView to data;
- whether or not you use the approach demonstrated by #Alex.T in your previous question;
- whether or no you read and understand the documentation;
BTW, the main question is - have you contacted the DevExpress team direcly and what their guys said?
for (int i = 0; i < gridView1.RowCount; i++)
{
// can't get answer of last record so i added test line in the last record to get all answers without new last record
if (i==gridView1.RowCount-1)
{
continue;
}
int rowHandle = gridView1.GetVisibleRowHandle(i);
string ResultAnswer = (string)gridView1.GetRowCellValue(rowHandle, "Answer");
string ResultQuest = (string)gridView1.GetRowCellValue(rowHandle, "Question");
}
I want to access the elements in the DataGrid.I am using following code.But I am unable to get the row of DataGrid.I am getting null value.I just want to know why I am getting null value and how to resolve this issue.
int itemscount = (dgMtHdr.Items.Count);
dgMtHdr.UpdateLayout();
for (int rowidx = 0; rowidx < itemscount; rowidx++)
{
Microsoft.Windows.Controls.DataGridRow dgrow = (Microsoft.Windows.Controls.DataGridRow)this.dgMtHdr.ItemContainerGenerator.ContainerFromIndex(rowidx);
if (dgrow != null)
{
DataRow dr = ((DataRowView)dgrow.Item).Row;
if (dr != null)
{
obj = new WPFDataGrid();
Microsoft.Windows.Controls.DataGridCell cells = obj.GetCell(dgMtHdr, rowidx, 7);
if (cells != null)
{
ContentPresenter panel = cells.Content as ContentPresenter;
if (panel != null)
{
ComboBox cmb = obj.GetVisualChild<ComboBox>(panel);
}
}
}
}
}
DataGrid internally hosts items in DataGridRowsPresenter which derives from VirtualizingStackPanel which means items rendered on UI by default support Virtualization i.e. ItemContainer won't be generated for items which are not rendered on UI yet.
That's why you getting null when you try to fetch rows which are not rendered on UI.
So, in case you are ready to trade off with Virtualization, you can turn off the Virtualization like this -
<DataGrid x:Name="dgMtHdr" VirtualizingStackPanel.IsVirtualizing="False"/>
Now, DataGridRow won't be null for any index value.
OR
You can get the row by manually calling UpdateLayout() and ScrollIntoView() for the index so that container gets generated for you. For details refer to this link here. From the link -
if (row == null)
{
// May be virtualized, bring into view and try again.
grid.UpdateLayout();
grid.ScrollIntoView(grid.Items[index]);
row = (DataGridRow)grid.ItemContainerGenerator.ContainerFromIndex(index);
}
EDIT
Since your DataGrid is in second tab which is not rendered yet. That's why its ItemContainerGenerator haven't generated corresponding containers required for items. So, you need to do it once item container is generated by hooking to StausChanged event -
dgMtHdr.ItemContainerGenerator.StatusChanged += new
EventHandler(ItemContainerGenerator_StatusChanged);
void ItemContainerGenerator_StatusChanged(object sender, EventArgs e)
{
if ((sender as ItemContainerGenerator).Status ==
GeneratorStatus.ContainersGenerated)
{
// ---- Do your work here and you will get rows as you intended ----
// Make sure to unhook event here, otherwise it will be called
// unnecessarily on every status changed and moreover its good
// practise to unhook events if not in use to avoid any memory
// leak issue in future.
dgMtHdr.ItemContainerGenerator.StatusChanged -=
ItemContainerGenerator_StatusChanged;
}
}
Using datagridview bound to BindingSource control bound to a LINQ to SQL class, I wonder how to position the bindingSource to a specific record, that is, when I type a Product name in a textbox, the bindingsource should move to that specific product. Here is my code:
In my form FrmFind:
NorthwindDataContext dc;
private void FrmFind_Load(object sender, EventArgs e)
{
dc = new NorthwindDataContext();
var qry = (from p in dc.Products
select p).ToList();
FindAbleBindingList<Product> list = new FindAbleBindingList<Product>(qry);
productBindingSource.DataSource = list.OrderBy(o => o.ProductName);
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
TextBox tb = sender as TextBox;
int index = productBindingSource.Find("ProductName", tb.Text);
if (index >= 0)
{
productBindingSource.Position = index;
}
}
In the program class:
public class FindAbleBindingList<T> : BindingList<T>
{
public FindAbleBindingList()
: base()
{
}
public FindAbleBindingList(List<T> list)
: base(list)
{
}
protected override int FindCore(PropertyDescriptor property, object key)
{
for (int i = 0; i < Count; i++)
{
T item = this[i];
//if (property.GetValue(item).Equals(key))
if (property.GetValue(item).ToString().StartsWith(key.ToString()))
{
return i;
}
}
return -1; // Not found
}
}
How can I implement the find method to make it work?
You can combine the BindingSource.Find() method with the Position property.
For example, if you have something like this in your TextBox changed event handler:
private void textBox1_TextChanged(object sender, EventArgs e)
{
TextBox tb = sender as TextBox;
int index = bs.Find("Product", tb.Text);
if (index >= 0)
{
bs.Position = index;
}
}
This of course will depend on a lot of things like the particular implementation of the Find method the data source for the binding source has.
In a question you asked a little while ago I gave you an implementation for Find which worked with full matches. Below is a slightly different implementation that will look at the start of the property being inspected:
protected override int FindCore(PropertyDescriptor property, object key)
{
// Simple iteration:
for (int i = 0; i < Count; i++)
{
T item = this[i];
if (property.GetValue(item).ToString().StartsWith(key.ToString()))
{
return i;
}
}
return -1; // Not found
}
Do note that the above method is case sensitive - you can change StartsWith to be case insensitive if you need.
One key thing to note about the way .Net works is that the actual type of an object is not sufficient all the time - the declared type is what consuming code knows about.
This is the reason why you get a NotSupported exception when calling the Find method, even though your BindingList implementation has a Find method - the code that receives this binding list doesn't know about the Find.
The reason for that is in these lines of code:
dc = new NorthwindDataContext();
var qry = (from p in dc.Products
select p).ToList();
FindAbleBindingList<Product> list = new FindAbleBindingList<Product>(qry);
productBindingSource.DataSource = list.OrderBy(o => o.ProductName);
When you set the data source for the binding source you include the extension method OrderBy - Checking this shows that it returns IOrderedEnumerable, an interface described here on MSDN. Note that this interface has no Find method, so even though the underlying FindableBindingList<T> supports Find the binding source doesn't know about it.
There are several solutions (the best is in my opinion to extend your FindableBindingList to also support sorting and sort the list) but the quickest for your current code is to sort earlier like so:
dc = new NorthwindDataContext();
var qry = (from p in dc.Products
select p).OrderBy(p => p.ProductName).ToList();
FindAbleBindingList<Product> list = new FindAbleBindingList<Product>(qry);
productBindingSource.DataSource = list;
In WinForms there are no entirely out of the box solutions for the things you are trying to do - they all need a little bit of custom code that you need to put together to match just your own requirements.
I took a different approach. I figured, programmatically, every record must be checked until a match is found, so I just iterated using the MoveNext method until I found a match. Unsure if the starting position would be the First record or not, so I used the MoveFirst method to ensure that is was.
There is one assumption, and that is that what you are searching for is unique in that column. In my case, I was looking to match an Identity integer.
int seekID;
this.EntityTableBindingSource.MoveFirst();
if (seekID > 0)
{
foreach (EntityTable sd in EntityTableBindingSource)
{
if (sd.ID != seekID)
{
this.t_EntityTableBindingSource.MoveNext();
}
else
{
break;
}
}
}
I didn't really care for either answer provided. Here is what I came up with for my problem:
// Create a list of items in the BindingSource and use labda to find your row:
var QuickAccessCode = customerListBindingSource.List.OfType<CustomerList>()
.ToList().Find(f => f.QuickAccessCode == txtQAC.Text);
// Then use indexOf to find the object in your bindingSource:
var pos = customerListBindingSource.IndexOf(QuickAccessCode);
if (pos < 0)
{
MessageBox.Show("Could not find " + txtQAC.Text);
}
else
{
mainFrm.customerListBindingSource.Position = pos;
}
I have my custom grid which inherits from DataGrid (from WPFToolkit) that has around 10000 items in it. The built-in sort is very slow. As such I have written a separate class that keeps a running sort of all the DataRowView items for each column (this works because additions and removals from the grid are extremely seldom, if ever).
The grid has AutoGenerateColumns='True' and is bound to the DefaultView of a DataTable.
I override the OnSorting to know when a column header is clicked and try to replace the ItemsSource of the grid with my sorted list of DataRowView. Below is the method:
private void RefreshItems()
{
if (_updating || _multiIndexer.Count == 0)
return;
try
{
_updating = true;
this.AutoGenerateColumns = false;
// replace the itemssource with my maintained and sorted list of
// DataRowView items
this.ItemsSource = _multiIndexer.ToList();
}
finally
{
//this.AutoGenerateColumns = true;
_updating = false;
}
}
The problem is that I destroy the columns that existed from the auto-generation. Also, I'm only left with columns that match the properties from DataRowView.
I believe the best approach would be to create a DataView from my sorted list of DataRowView and pass that to the ItemsSource but I have yet to have any success.
Any ideas how to pass a new list of rows to the ItemsSource or Items without destroying the auto-generated columns? Generating all my columns manually is not an option.
Cheers,
Sean
I'm not aware of a way to get rid of re-creation of the columns. I'm having a similar problem, and usually I'm using ICollectionView and DeferRefresh. Because you don't have to do it in your actual model object. But I'm not sure if it works with DataViews as well as good as with List.
what do you mean by "its very slow"?
if i take a datagrid and bind a datatable with 50000row and 20columns to it. it seems fast to me
viewmodel
public class Viewmodel
{
public DataTable MyData { get; set; }
public Viewmodel()
{
this.MyData = new DataTable();
for (int i = 0; i < 20; i++)
{
this.MyData.Columns.Add("Col" + i);
}
for (int i = 0; i < 50000; i++)
{
var row = MyData.NewRow();
for (int j = 0; j < 20; j++)
{
row["Col" + j] = string.Format("{0} Row, Col {1}", i, j);
}
this.MyData.Rows.Add(row);
}
}
}
window
<DataGrid ItemsSource="{Binding MyData}" AutoGenerateColumns="True">
</DataGrid>
edit: its .net4.0
I have a ListBox or DataGrid filled with thousands of entries. I would like to know items that the user has looked at (scrolling, searching or otherwise). How can I tell what is visible to the user in the ListBox?
Bonus: Set a timer so that the item has to be shown for a minimum of N milliseconds (in the event the user is just pulling down the scrollbar).
Update: This is a near duplicate of Get items in view within a listbox - but the solution it gives, using "SelectedItems", is not sufficient. I need to know the items whether they are selected or not!
All you need to do is to get the underlying StackPanel that's inside the ListBox. It has enough information about which elements are showing. (It implements the interface IScrollInfo).
To get the underlying StackPanel (or actually VirtualizingStackPanel) from a given ListBox, we'll have to use VisualTreeHelper to go through the Visual Tree and look for the VirtualizingStackPanel, like so:
private VirtualizingStackPanel GetInnerStackPanel(FrameworkElement element)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(element); i++)
{
var child = VisualTreeHelper.GetChild(element, i) as FrameworkElement;
if (child == null) continue;
Debug.WriteLine(child.ToString());
if (child is VirtualizingStackPanel) return child as VirtualizingStackPanel;
var panel = GetInnerStackPanel(child);
if (panel != null)
return panel;
}
return null;
}
Now that we have the StackPanel, we're very close. The StackPanel has the properties VerticalOffset and ViewportHeight (both coming from IScrollInfo) that can give us all the information we need.
private void button1_Click(object sender, RoutedEventArgs e)
{
var theStackPanel = GetInnerStackPanel(MyListBox);
List<FrameworkElement> visibleElements = new List<FrameworkElement>();
for (int i = 0; i < theStackPanel.Children.Count; i++)
{
if (i >= theStackPanel.VerticalOffset && i <= theStackPanel.VerticalOffset + theStackPanel.ViewportHeight)
{
visibleElements.Add(theStackPanel.Children[i] as FrameworkElement);
}
}
MessageBox.Show(visibleElements.Count.ToString());
MessageBox.Show(theStackPanel.VerticalOffset.ToString());
MessageBox.Show((theStackPanel.VerticalOffset + theStackPanel.ViewportHeight).ToString());
}