简体   繁体   中英

Updating a cell in DataGrid using C#.net

I found ListView very slow for my program. Therefore i decided to move to DataGrid.

Before this, I only used to list the data from database source.

I used following code to add new row to the 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 ". 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. How can i do same in DataGrid.

I am using 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.

为什么您不能将数据对象列表绑定到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:

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

gridView1.DataSource = dt;

and now changes made on gridView will update your DataTable too :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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