wpf 将数据添加到 DataGrid 中的特定列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35221658/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Adding data to a specific column in a DataGrid
提问by CareTaker22
I want to create a new column and then add values to onlythat new column on a button click event. Is that possible? The column might have a few rows underneath it, depending the amount of items in a quote.
我想创建一个新列,然后在按钮单击事件中仅向该新列添加值。那可能吗?该列下面可能有几行,具体取决于报价中的项目数量。
What I have achieved so far:
到目前为止我所取得的成就:
My class where all my information is stored in
我所有信息都存储在我的班级
public class ViewQuoteItemList
{
...
public double SupplierCost { get; set; }
...
}
I can create my column and bind it to my ViewQuoteItemListclass
我可以创建我的专栏并将其绑定到我的ViewQuoteItemList班级
DataGridTextColumn columnFeedbackSupplier = new DataGridTextColumn();
columnFeedbackSupplier.Binding = new Binding("SupplierCost");
//The header of the column gets it's value from a combobox where you select a company to be added to the datagrid
columnFeedbackSupplier.Header = (cmbFeedbackSelectSupplier.SelectedItem as DisplayItems).Name;
From here I get my quote items from a different datagrid and I add them to my second datagrid where I want to add the new column and it's values
从这里我从不同的数据网格中获取我的报价项,然后将它们添加到我想要添加新列及其值的第二个数据网格中
IList list = dgFeedbackAddCost.SelectedItems as IList;
IEnumerable<ViewQuoteItemList> items = list.Cast<ViewQuoteItemList>();
var collection = (from i in items
let a = new ViewQuoteItemList { SupplierCost = 0 }
select a).ToList();
Lastly, I add the new column to the second datagrid and set the collectionas the datagrid's ItemSource
最后,我将新列添加到第二个数据网格并将其设置collection为数据网格的ItemSource
dgFeedbackSelectSupplier.Columns.Add(columnFeedbackSupplier);
dgFeedbackSelectSupplier.ItemsSource = collection;
My problem is that once I edit a cell of data from one of the suppliers, the whole row gets updated with that one value, because it's all bound to one class/item source. Can this be fixed?
我的问题是,一旦我编辑了其中一个供应商的数据单元格,整行都会更新为该值,因为它都绑定到一个类/项目源。这可以解决吗?
EDIT:
编辑:
"The whole row gets updated" means that every time I insert a value into one cell in a row, every single cell in that row gets updated with the same value. Here are some pictures showing what I mean. I want to editall the data and this all happens on my second datagrid(dgFeedbackSupplier).
“整行被更新”意味着每次我将一个值插入一行中的一个单元格时,该行中的每个单元格都会更新为相同的值。这里有一些图片显示了我的意思。我想编辑所有数据,这一切都发生在我的第二个数据网格(dgFeedbackSupplier)上。
Here, I have two companies added with the 4 items that I want to compare prices with. Now I want to click on a single cell underneath a company and add a value for a certain item.
在这里,我有两家公司添加了我想要比较价格的 4 个项目。现在我想单击公司下方的单个单元格并为某个项目添加一个值。
Here I double click on a cell to edit/change the value.
Then when I change my value in the selected cell, every other company's value for that specific item in the same row gets updated with that same value.

然后,当我更改所选单元格中的值时,同一行中该特定项目的所有其他公司的值都会更新为相同的值。

That's my problem and I need to have only that one cell's value changed, and not the whole row.
那是我的问题,我只需要更改一个单元格的值,而不是整行。
EDIT 2:
编辑2:
How can I convert this collectionto ExpandoObject?
我怎样才能把它转换collection成ExpandoObject?
var collection = (from i in items
let a = new ViewQuoteItemList { Item = i.Item, Supplier = 25 }
select a).ToList();
EDIT 3:
编辑 3:
My XAML:
我的 XAML:
<DataGrid x:Name="dgFeedbackSelectSupplier" Margin="245,266,0,32" BorderBrush="#FFADADAD" ColumnWidth="*" AutoGenerateColumns="True" CanUserAddRows="False">
<DataGrid.Columns>
<DataGridTextColumn x:Name="columnFeedbackSupplierItem" IsReadOnly="True" Header="Item" Binding="{Binding Item}"/>
</DataGrid.Columns>
</DataGrid>
And this is how my whole method looks like at the moment where I add my Columns and where I get the items from my other datagrid:
这就是在我添加列以及从其他数据网格获取项目时我的整个方法的样子:
private void btnFeedbackSelectSupplier_Click(object sender, RoutedEventArgs e)
{
supplier.Id = (cmbFeedbackSelectSupplier.SelectedItem as DisplayItems).Id;//Not using yet
supplier.Name = (cmbFeedbackSelectSupplier.SelectedItem as DisplayItems).Name;
DataGridTextColumn columnFeedbackSupplier = new DataGridTextColumn();
columnFeedbackSupplier.Binding = new Binding("Supplier") { Mode = BindingMode.TwoWay };
columnFeedbackSupplier.CanUserReorder = true;
columnFeedbackSupplier.CanUserResize = true;
columnFeedbackSupplier.IsReadOnly = false;
columnFeedbackSupplier.Header = supplier.Name;
dgFeedbackAddCost.SelectAll();
IList list = dgFeedbackAddCost.SelectedItems as IList;
IEnumerable<ViewQuoteItemList> items = list.Cast<ViewQuoteItemList>();
var collection = new List<ExpandoObject>();
foreach (var i in items)
{
dynamic a = new ExpandoObject();
a.Id = (cmbFeedbackSelectSupplier.SelectedItem as DisplayItems).Id;
a.Item = i.Item;
a.Supplier = 25;
collection.Add(a);
}
dgFeedbackSelectSupplier.Columns.Add(columnFeedbackSupplier);
dgFeedbackSelectSupplier.ItemsSource = collection;
}
采纳答案by CareTaker22
I see that this question is getting quite a bit of attention, so I will post the solution to my answer. I hope this will help someone out there to get some idea on how to add data only to a specific column. :)
我看到这个问题受到了相当多的关注,所以我会将解决方案发布到我的答案中。我希望这会帮助那里的人了解如何仅将数据添加到特定列。:)
Just as a side note - This is a test application that I created, therefore the coding will not be the same as the coding in my original question. Also I used a dictionary to solve my problem. It works great!
顺便提一下 - 这是我创建的一个测试应用程序,因此编码将与我原始问题中的编码不同。我也用字典来解决我的问题。效果很好!
Creating my Item and Supplier lists:
创建我的项目和供应商列表:
//I create my dummy suppliers
private string[] CONST_Supplies = { "Supplier 1", "Supplier 2", "Supplier 3", "Supplier 4" };
public MainWindow()
{
InitializeComponent();
//I add my dummy items into my datagrid
//These are the items that I want to compare prices with
List<ViewQuoteItemList> list = new List<ViewQuoteItemList>();
list.Add(new ViewQuoteItemList() { Item = "Item 1" });
list.Add(new ViewQuoteItemList() { Item = "Item 2" });
list.Add(new ViewQuoteItemList() { Item = "Item 3" });
list.Add(new ViewQuoteItemList() { Item = "Item 4" });
list.Add(new ViewQuoteItemList() { Item = "Item 5" });
list.Add(new ViewQuoteItemList() { Item = "Item 6" });
//Loading the items into the datagrid on application start
DataGridTest.ItemsSource = list;
//Adding my dummy suppliers to my supplier selection combobox
foreach (var supplier in CONST_Supplies)
ComboBoxTest.Items.Add(supplier);
}
My button click event:
我的按钮点击事件:
private void Add_Click(object sender, RoutedEventArgs e)
{
//Select my supplier from my Supplier's combobox
var supplier = ComboBoxTest.SelectedItem as string;
//Create the Supplier column and bind it to my 'ViewQuoteItemList' class +
//I'm binding it to the unique supplier selected from my combobox
DataGridTextColumn columnFeedbackSupplier = new DataGridTextColumn();
columnFeedbackSupplier.Binding = new Binding("Suppliers[" + supplier + "]");
columnFeedbackSupplier.Binding.FallbackValue = "Binding failed";
columnFeedbackSupplier.CanUserReorder = true;
columnFeedbackSupplier.CanUserResize = true;
columnFeedbackSupplier.IsReadOnly = false;
columnFeedbackSupplier.Header = ComboBoxTest.SelectedItem as string;
foreach (var item in DataGridTest.ItemsSource as List<ViewQuoteItemList>)
if (!item.Suppliers.ContainsKey(supplier))
item.Suppliers.Add(supplier, string.Empty);
DataGridTest.Columns.Add(columnFeedbackSupplier);
}
My class:
我的课:
public class ViewQuoteItemList
{
public ViewQuoteItemList()
{
Suppliers = new ObservableDictionary<string, string>();
}
public int Id { get; set; }
public string Item { get; set; }
public ObservableDictionary<string, string> Suppliers { get; set; }
}
And my Observable Dictionary where a lot of the work happens:
还有我的 Observable 字典,其中有很多工作发生:
public class ObservableDictionary<TKey, TValue> : IDictionary<TKey, TValue>, INotifyCollectionChanged, INotifyPropertyChanged
{
private const string CountString = "Count";
private const string IndexerName = "Item[]";
private const string KeysName = "Keys";
private const string ValuesName = "Values";
private IDictionary<TKey, TValue> _Dictionary;
protected IDictionary<TKey, TValue> Dictionary
{
get { return _Dictionary; }
}
#region Constructors
public ObservableDictionary()
{
_Dictionary = new Dictionary<TKey, TValue>();
}
public ObservableDictionary(IDictionary<TKey, TValue> dictionary)
{
_Dictionary = new Dictionary<TKey, TValue>(dictionary);
}
public ObservableDictionary(IEqualityComparer<TKey> comparer)
{
_Dictionary = new Dictionary<TKey, TValue>(comparer);
}
public ObservableDictionary(int capacity)
{
_Dictionary = new Dictionary<TKey, TValue>(capacity);
}
public ObservableDictionary(IDictionary<TKey, TValue> dictionary, IEqualityComparer<TKey> comparer)
{
_Dictionary = new Dictionary<TKey, TValue>(dictionary, comparer);
}
public ObservableDictionary(int capacity, IEqualityComparer<TKey> comparer)
{
_Dictionary = new Dictionary<TKey, TValue>(capacity, comparer);
}
#endregion
#region IDictionary<TKey,TValue> Members
public void Add(TKey key, TValue value)
{
Insert(key, value, true);
}
public bool ContainsKey(TKey key)
{
return Dictionary.ContainsKey(key);
}
public ICollection<TKey> Keys
{
get { return Dictionary.Keys; }
}
public bool Remove(TKey key)
{
if (key == null) throw new ArgumentNullException("key");
TValue value;
Dictionary.TryGetValue(key, out value);
var removed = Dictionary.Remove(key);
if (removed)
//OnCollectionChanged(NotifyCollectionChangedAction.Remove, new KeyValuePair<TKey, TValue>(key, value));
OnCollectionChanged();
return removed;
}
public bool TryGetValue(TKey key, out TValue value)
{
return Dictionary.TryGetValue(key, out value);
}
public ICollection<TValue> Values
{
get { return Dictionary.Values; }
}
public TValue this[TKey key]
{
get
{
return Dictionary[key];
}
set
{
Insert(key, value, false);
}
}
#endregion
#region ICollection<KeyValuePair<TKey,TValue>> Members
public void Add(KeyValuePair<TKey, TValue> item)
{
Insert(item.Key, item.Value, true);
}
public void Clear()
{
if (Dictionary.Count > 0)
{
Dictionary.Clear();
OnCollectionChanged();
}
}
public bool Contains(KeyValuePair<TKey, TValue> item)
{
return Dictionary.Contains(item);
}
public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
{
Dictionary.CopyTo(array, arrayIndex);
}
public int Count
{
get { return Dictionary.Count; }
}
public bool IsReadOnly
{
get { return Dictionary.IsReadOnly; }
}
public bool Remove(KeyValuePair<TKey, TValue> item)
{
return Remove(item.Key);
}
#endregion
#region IEnumerable<KeyValuePair<TKey,TValue>> Members
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
{
return Dictionary.GetEnumerator();
}
#endregion
#region IEnumerable Members
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable)Dictionary).GetEnumerator();
}
#endregion
#region INotifyCollectionChanged Members
public event NotifyCollectionChangedEventHandler CollectionChanged;
#endregion
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
#endregion
public void AddRange(IDictionary<TKey, TValue> items)
{
if (items == null) throw new ArgumentNullException("items");
if (items.Count > 0)
{
if (Dictionary.Count > 0)
{
if (items.Keys.Any((k) => Dictionary.ContainsKey(k)))
throw new ArgumentException("An item with the same key has already been added.");
else
foreach (var item in items) Dictionary.Add(item);
}
else
_Dictionary = new Dictionary<TKey, TValue>(items);
OnCollectionChanged(NotifyCollectionChangedAction.Add, items.ToArray());
}
}
private void Insert(TKey key, TValue value, bool add)
{
if (key == null) throw new ArgumentNullException("key");
TValue item;
if (Dictionary.TryGetValue(key, out item))
{
if (add) throw new ArgumentException("An item with the same key has already been added.");
if (Equals(item, value)) return;
Dictionary[key] = value;
OnCollectionChanged(NotifyCollectionChangedAction.Replace, new KeyValuePair<TKey, TValue>(key, value), new KeyValuePair<TKey, TValue>(key, item));
}
else
{
Dictionary[key] = value;
OnCollectionChanged(NotifyCollectionChangedAction.Add, new KeyValuePair<TKey, TValue>(key, value));
}
}
private void OnPropertyChanged()
{
OnPropertyChanged(CountString);
OnPropertyChanged(IndexerName);
OnPropertyChanged(KeysName);
OnPropertyChanged(ValuesName);
}
protected virtual void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
private void OnCollectionChanged()
{
OnPropertyChanged();
if (CollectionChanged != null) CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
}
private void OnCollectionChanged(NotifyCollectionChangedAction action, KeyValuePair<TKey, TValue> changedItem)
{
OnPropertyChanged();
if (CollectionChanged != null) CollectionChanged(this, new NotifyCollectionChangedEventArgs(action, changedItem));
}
private void OnCollectionChanged(NotifyCollectionChangedAction action, KeyValuePair<TKey, TValue> newItem, KeyValuePair<TKey, TValue> oldItem)
{
OnPropertyChanged();
if (CollectionChanged != null) CollectionChanged(this, new NotifyCollectionChangedEventArgs(action, newItem, oldItem));
}
private void OnCollectionChanged(NotifyCollectionChangedAction action, IList newItems)
{
OnPropertyChanged();
if (CollectionChanged != null) CollectionChanged(this, new NotifyCollectionChangedEventArgs(action, newItems));
}
}
It's a lot of code, I know. Sorry I don't have the time to explain everything and how it works. I hope that you guys can figure this out by yourself ;) There is also a lot of extra functions in the class that you can use for various purposes.
这是很多代码,我知道。抱歉,我没有时间解释一切以及它是如何工作的。我希望你们能自己解决这个问题;) 类中还有很多额外的功能,你可以用于各种目的。
Lastly, here is my XAML:
最后,这是我的 XAML:
<Button x:Name="Add" Content="Add" HorizontalAlignment="Left" Margin="65,143,0,0" VerticalAlignment="Top" Width="75" Click="Add_Click"/>
<DataGrid x:Name="DataGridTest" CanUserAddRows="False" AutoGenerateColumns="False" HorizontalAlignment="Left" Margin="165,115,0,0" VerticalAlignment="Top" Height="279" Width="611" ColumnWidth="*">
<DataGrid.Columns>
<DataGridTextColumn x:Name="columnFeedbackSupplierItem" Header="Item" Binding="{Binding Item}"/>
</DataGrid.Columns>
</DataGrid>
<ComboBox x:Name="ComboBoxTest" HorizontalAlignment="Left" Margin="20,115,0,0" VerticalAlignment="Top" Width="120"/>
Note - The values in the datagrid can be edited when you double-click on a cell. Thank you for all the people that added to my question or helped me in the right direction. I hope this can help someone out there.
注 - 双击单元格时可以编辑数据网格中的值。感谢所有添加到我的问题或在正确方向上帮助我的人。我希望这可以帮助那里的人。
回答by Orhan Tuncer
May I propose another approach? From what I understand;
我可以提出另一种方法吗?据我了解;
You have suppliers and these suppliers have items. You can add new suppliers. I assumed suppliers may not have all the items (for a challenge :)).
你有供应商,这些供应商有项目。您可以添加新的供应商。我认为供应商可能没有所有物品(为了挑战:))。
You want to present this data structure in a grid like view.
您想在类似视图的网格中呈现此数据结构。
The problem here is that you are trying to display a non-tabular data with a tabular view component. What you have is hierarchical data. Before I continue with my solution here are some screen shots.
这里的问题是您正在尝试使用表格视图组件显示非表格数据。您拥有的是分层数据。在我继续我的解决方案之前,这里有一些屏幕截图。
What I basically did here is to create new views on the hierarchical data, filling the gaps and turn it into a tabular form. I used fake classes for the empty slots so I could easily select the proper datatemplates in XAML. I avoided to use any custom code and kept everything in MVVM+XAML way. So bindings and such works as expected.
我在这里所做的基本上是在分层数据上创建新视图,填补空白并将其转换为表格形式。我为空槽使用了假类,因此我可以轻松地在 XAML 中选择正确的数据模板。我避免使用任何自定义代码,并以 MVVM+XAML 方式保留所有内容。因此绑定和此类工作按预期进行。
The new views had to be updated when the collections changed, so I used the messenger class from MVVMLight for easy implementation, and called RaisePropertyChanged events manually.
新视图必须在集合更改时更新,因此我使用 MVVMLight 中的 messenger 类来轻松实现,并手动调用 RaisePropertyChanged 事件。
In XAML I used ItemsControl and UniformGrid components to create the grid like view.
在 XAML 中,我使用 ItemsControl 和 UniformGrid 组件来创建类似视图的网格。
I put the complete solution on GitHub: https://github.com/orhtun/GridLikeViewWithDynamicColumns
我把完整的解决方案放在GitHub 上:https: //github.com/orhtun/GridLikeViewWithDynamicColumns
It creates random data on each run. If you get build errors, try right click on the solution and Restore NuGet Packages.
它在每次运行时创建随机数据。如果您遇到构建错误,请尝试右键单击解决方案并恢复 NuGet 包。
回答by Kylo Ren
You can't use a collection to bind with your second DataGrid cause your view is dynamic can can have variable no of columns.
您不能使用集合与您的第二个 DataGrid 绑定,因为您的视图是动态的,并且可以具有可变的列数。
You should use a DataTable as a source to your DataGrid. Instead of adding a column in grid add a column in DataTable and AutoGenerate the column in the Grid.
您应该使用 DataTable 作为 DataGrid 的源。不是在网格中添加一列,而是在 DataTable 中添加一列并自动生成网格中的列。
A method to transform item source(any type) to DataTable is(may be you need this first time):
将项目源(任何类型)转换为 DataTable 的方法是(可能是您第一次需要):
public static DataTable DataGridtoDataTable(DataGrid dg)
{
dg.SelectAllCells();
dg.ClipboardCopyMode = DataGridClipboardCopyMode.IncludeHeader;
ApplicationCommands.Copy.Execute(null, dg);
dg.UnselectAllCells();
String result = (string)Clipboard.GetData(DataFormats.CommaSeparatedValue);
string[] Lines = result.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);
string[] Fields;
Fields = Lines[0].Split(new char[] { ',' });
int Cols = Fields.GetLength(0);
DataTable dt = new DataTable();
for (int i = 0; i < Cols; i++)
dt.Columns.Add(Fields[i].ToUpper(), typeof(string));
DataRow Row;
for (int i = 1; i < Lines.GetLength(0) - 1; i++)
{
Fields = Lines[i].Split(new char[] { ',' });
Row = dt.NewRow();
for (int f = 0; f < Cols; f++)
{
Row[f] = Fields[f];
}
dt.Rows.Add(Row);
}
return dt;
}
then later when you have to add a column in the DataGrid, add a column in a table by iterating on collectionto fill your column in data table.
然后稍后当您必须在 DataGrid 中添加一列时,通过迭代collection填充数据表中的列在表中添加一列。
There is no simple way to do your problem as your scenario is unique and only a dynamic structure can fullfill your need.
没有简单的方法可以解决您的问题,因为您的场景是独一无二的,只有动态结构才能满足您的需求。
Since by using the DataTable your all cell will be bound to unique entities. Only one cell will get updated on a single change of DataGrid cell.(Unlike collection where multiple cells are bound to same property)
由于使用 DataTable,您的所有单元格都将绑定到唯一实体。DataGrid 单元格的一次更改只会更新一个单元格。(与多个单元格绑定到同一属性的集合不同)
回答by Muds
For your requirement I would suggest you to use Microsoft DynamicsExpandoObject
根据您的要求,我建议您使用Microsoft DynamicsExpandoObject
You need to create a List<ExpandoObject>which is nothing but a Dictionary<string,object>wherein your key is your property name and object is your value. So in your case,
您需要创建一个List<ExpandoObject>只是 a ,Dictionary<string,object>其中您的键是您的属性名称,而对象是您的值。所以在你的情况下,
All the properties in ViewQuoteItemare added to this new Object and when you need to add a column you can add another property to your object. Then just update your view and see new column added to grid.
中的所有属性ViewQuoteItem都添加到这个新对象中,当您需要添加列时,您可以向对象添加另一个属性。然后只需更新您的视图并查看添加到网格的新列。
To use Expando, you can either do it the easy way -
要使用 Expando,您可以通过简单的方法进行操作 -
var dynamicItem = New ExpandoObject();
dynamicItem.Item = "Test";
dynamicItem.BarlwoodCityDeep = (int)350;
or you can treat dynamicItem as dictionary like this -
或者您可以将 dynamicItem 视为这样的字典 -
IDictionary<String, Object> dynamicDict = dynamicItem
dynamicDict.Add("MyNewProperty","MySomeValue")
I personally find converting to Dicteasy as it gives me flexibility to add properties explicitly and then use keys to refer to them but its just an ease not compulsion.
我个人认为转换为Dict容易,因为它让我可以灵活地显式添加属性,然后使用键来引用它们,但这只是一种轻松而不是强迫。
I would also recommend you to have a method that maps your dataList to new expandoList and bind expandlist to your view, please make sure that you use AutoGeneration of columns in WPF so that newly added columns are visible.
我还建议您使用一种方法将您的 dataList 映射到新的 expandoList 并将 expandlist 绑定到您的视图,请确保您在 WPF 中使用自动生成列,以便新添加的列可见。
You can have a look at my solution herethat worked for me in somewhat similar case.
您可以在这里查看我的解决方案,该解决方案在有些类似的情况下对我有用。
If you are new to dynamics, you might find it bit tricky but Expandos are treat to work with and ease to work with them is amazing.
如果您是dynamics.
to convert from ViewQuoteItemList to Expando --
从 ViewQuoteItemList 转换为 Expando --
var collection = new List<ExpandoObject>();
foreach (var i in items)
{
dynamic a = new ExpandoObject();
a.Item = i.item;
a.Supplier = 25;
collection.Add(a);
}
回答by Nate M.
Personally, I would keep away from actually instantiating individual columns, instead add them to the DataGridView directly, and then manipulate their properties.
就个人而言,我会避免实际实例化单个列,而是直接将它们添加到 DataGridView,然后操作它们的属性。
List<MyClass> myList = new List<MyClass>();
BindingList<MyClass> bList = new BindingList<MyClass>(myList);
myDataGridView.DataSource = new BindingSource(bList,null);
//Now Lets add a custom column..
myDataGridView.Columns.Add("Text","Text");
//Now lets edit it's properties
myDataGridView.Columns["Text"].ReadOnly = false;
myDataGridView.EditMode = DataGridViewEditMode.EditOnKeystroke;
//Now lets walk through and throw some data in each cell..
if(myDataGridView.Rows.Count > 1)
{
for(int i = 0;i < myDataGridView.Rows.Count;i++)
{
myDataGridView.Rows[i].Cells["Text"].Value = "My Super Useful Text";
}
}
Avoiding use of instantiating the column, and then adding it has helped me in the past with weird linkage issues, for instance editing one cell, and others change. As for sub-views etc, I can't say I can comment much on that.
避免使用实例化列,然后添加它在过去帮助我解决了奇怪的链接问题,例如编辑一个单元格,而其他单元格发生变化。至于子视图等,我不能说我可以对此发表太多评论。

