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.
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 :)
Why can you not bind your data object list to the Datagrid, and after you have just to modify the data object list and it's done!
精彩评论