How can I access a specific cell by index in a DataGridViewRow? Regular DataGridView has Rows parameter, DataGridViewRow doesn't have it
var GridRow = new DataGridViewRow();
GridRow.Cells.Add(cell1);
GridRow.Cells.Add(cell);
GridRow.Cells[1].Value = true;
CodePudding user response:
I guess this is what you want to achieve?
int index = yourDGV.Rows.Add(GridRow);
//Get newly added row
var row = yourDGV.Rows[index];
//value of cell
var value = row.Cells[1].Value
CodePudding user response:
It's better to strong type data in a DataGridView in tangent with utilizing a BindingSource. The BindingSource provides access to data in the DataGridView without the need to touch rows/cells in the DataGridView.
Simple example, for indexing into the data a NumericUpDown control gets the index into the data and if in range shows current data while the second method accesses the current row via BindingSource.Current property which is an object that we need to cast to the underlying type, same with the index method.
Simple model
public class Item
{
public bool Check { get; set; }
public string Name { get; set; }
public int Quantity { get; set; }
}
Form code
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace YourNamespaceGoesHere
{
public partial class ExampleForm : Form
{
private readonly BindingSource _bindingSource = new BindingSource();
public ExampleForm()
{
InitializeComponent();
_bindingSource.DataSource = new List<Item>()
{
new Item() {Check = false, Name = "Apples", Quantity = 1},
new Item() {Check = true, Name = "Oranges", Quantity = 0},
};
dataGridView1.DataSource = _bindingSource;
}
private void ByIndexButton_Click(object sender, EventArgs e)
{
int index = (int)numericUpDown1.Value;
if (index <= _bindingSource.Count -1)
{
var item = (Item)_bindingSource[index];
MessageBox.Show($"{(item.Check ? "Yes" : "No"),-5}{item.Name}{item.Quantity,4}");
}
else
{
MessageBox.Show($"{index} is out of range");
}
}
private void CurrentButton_Click(object sender, EventArgs e)
{
if (_bindingSource.Current != null)
{
var item = (Item)_bindingSource.Current;
MessageBox.Show($"{(item.Check ? "Yes" : "No"), -5}{item.Name}{item.Quantity,4}");
}
}
}
}