Using GridView with DataTable in C#
Define the GridView with DataTable
//define DataTableDataTable dt = new DataTable("dataTable");dt.Columns.Add("Id", typeof(int));dt.Columns.Add("Name", typeof(string));//add DataRowDataRow row = dt.NewRow();row["Id"] = 1;row["Name"] = "One";dt.Rows.Add(row);//assign to gridViewgridView.DataSource = dt;
Get data from selected Row in GridView
//get data from selected rowprivate void gridView_SelectionChanged(object sender, EventArgs e){if (gridView.SelectedCells.Count > 0){int seletedRow = gridView.SelectedCells[0].RowIndex;DataRow row = ((DataTable) gridView.DataSource).Rows[seletedRow];int id = (int)row["Id"];string name = (string)row["Name"];}}
Change Column colours
private void gridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e){DataGridViewRow row = gridView.Rows[e.RowIndex];if (e.RowIndex < ((DataTable)gridView.DataSource).Rows.Count){if (((DataTable)gridView.DataSource).Rows[e.RowIndex].RowState != DataRowState.Unchanged){row.DefaultCellStyle.BackColor = Color.LightYellow;}}else{row.DefaultCellStyle.BackColor = Color.LightYellow;}}
Comments
Post a Comment