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";
dt.Rows.Add(row);
//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;
    }
  }else{
    row.DefaultCellStyle.BackColor = Color.LightYellow;
  }
}

Comments

Popular posts from this blog

Parse XML to dynamic object in C#

C# Updating GUI from different thread