简体   繁体   English

使用C#.net更新DataGrid中的单元格

[英]Updating a cell in DataGrid using C#.net

I found ListView very slow for my program. 我发现ListView对于我的程序非常慢。 Therefore i decided to move to DataGrid. 因此,我决定移至DataGrid。

Before this, I only used to list the data from database source. 在此之前,我仅用于列出数据库源中的数据。

I used following code to add new row to the DataGrid: 我使用以下代码向DataGrid添加新行:

        DataGridViewRow row = new DataGridViewRow();
        row.CreateCells(MyGrid);  
        row.Cells[0].Value = "1";  
        MyGrid.Rows.Add(row);
        row.Cells["Category"].Value = "Vegetables";
        row.Cells["Item"].Value = "Carrot";
        row.Cells["Price"].Value = "12.50";

I've used similar pattern to add new row for different things. 我使用类似的模式为不同的事物添加新行。 Also let me know if there is any better method to directly add variables to the database. 还请让我知道是否有更好的方法直接将变量添加到数据库。

The main thing i wanted to know is how to edit the cell data. 我想知道的主要事情是如何编辑单元格数据。

For example I have following data table: 例如,我有以下数据表:

ID    ITEM     Price
1    item A     100
2    item B     120
3    item C     121
4    item D     103

And I want to change the price value of item B from " 120 " to " 210 ". 我想将项目B的价格值从“ 120 ”更改为“ 210 ”。 how can i achieve this? 我怎样才能做到这一点?

In ListView i looked for column with value item B and get the column index of price and replaced the value. 在ListView中,我查找了带有值项B的列,并获得了价格的列索引并替换了值。 How can i do same in DataGrid. 我该怎么做在DataGrid中。

I am using C#.net 我正在使用C#.net

Additional note: The list generated is a dynamic list there for I'll need to find the cell with value item B and then change the value of price column of respective row. 补充说明:生成的列表是一个动态列表,因为我需要找到带有值项目B的单元格,然后更改相应行的价格列的值。

为什么您不能将数据对象列表绑定到Datagrid,而仅在修改数据对象列表之后就完成了!

First, Create your custom DataTable 首先,创建您的自定义数据表

DataTable dt = new DataTable();
dt.Columns.Add("Id",typeof(int));
dt.Columns.Add("Item",typeof(string));
dt.Columns.Add("Price",typeof(decimal));
dt.AcceptChanges(); // This is the point, where you can change dataTable items.

and add your items to your DataTable rows like: 并将您的项目添加到DataTable行中,例如:

foreach(var rowItem in blabla)
{
object[] row = new object[]
{
rowItem.Id,
rowItem.Item,
rowItem.Price
};
dt.Rows.Add(row);
}

and then bind dataTable to gridView 然后将dataTable绑定到gridView

gridView1.DataSource = dt;

and now changes made on gridView will update your DataTable too :) 现在在gridView上所做的更改也会更新您的DataTable :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM