Using GridView with DataTable in C#

Define the GridView with DataTable

//define DataTable
DataTable dt = new DataTable("dataTable");
dt.Columns.Add("Id", typeof(int));
dt.Columns.Add("Name", typeof(string));
//add DataRow
DataRow row = dt.NewRow();
row["Id"] = 1;
row["Name"] = "One";
//assign to gridView
gridView.DataSource = dt;

Get data from selected Row in GridView

//get data from selected row
private 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;
    row.DefaultCellStyle.BackColor = Color.LightYellow;


Popular posts from this blog

Parse XML to dynamic object in C#

Parse XML to object model in C# using XSD utility