How to update changed row color on DataGridView (in tabs)

  • Thread starter Thread starter Jonas Andersson
  • Start date Start date
J

Jonas Andersson

Guest
I have a number of tabs with with a DataGridView on each. When I change the row color on some of the GridViews the change doesnt take place until I click the last tab. Then going back to the other tabs, first then, I can see that the row colour has changed.

What do I need to update in order for the change to take place, without the need to click the last tab?


//Read Data from the First Sheet.
using (OleDbConnection con = new OleDbConnection(conStr))
{
using (OleDbCommand cmd = new OleDbCommand())
{
using (OleDbDataAdapter oda = new OleDbDataAdapter())
{
int pageNumber = 0;
for (int i = 0; i < stringArray.Length; i++)
{
DataTable dt = new DataTable();
cmd.CommandText = "SELECT * From [" + stringArray + "]";
cmd.Connection = con;
con.Open();
oda.SelectCommand = cmd;
oda.Fill(dt);
con.Close();

//Populate DataGridView.

/* Dynamic DataGridView */
dgwDynamic = new DataGridView();
dgwDynamic.Name = "DataGridView" + stringArray.ToString();
dgwDynamic.ScrollBars = ScrollBars.Both;
dgwDynamic.Dock = DockStyle.Fill;
dgwDynamic.DataBindingComplete += dgwDynamic_DataBindingComplete;


/* Dynamic TabPage */
TabPage tpDynamic = new TabPage();
pageNumber = i + 1;
tpDynamic.Name = "tabPage" + pageNumber.ToString();
//tpDynamic.Text = stringArray;

string[] splitString = stringArray.Split($);
string firstSixCharacters = splitString[0]; //Keep first 6 characters
string tabName = firstSixCharacters.Remove(0, 1); //Remove first character, resulting in 5 characters

tpDynamic.Text = tabName;

tpDynamic.TabIndex = i;
// One newGridView per newTabPage
tpDynamic.Controls.Add(dgwDynamic); // Add Dynamic DataGridView to Dynamic TabPage
tabControl1.Controls.Add(tpDynamic); // Add Dynamic TabPage to TabControl
dgwDynamic.DataSource = dt; // Add DataTable to Dynamic DataGridView


}//End for loop
dgwDynamic.CellFormatting += dgwDynamic_CellFormatting; // Change row colour


//Im trying this but nothing happens
dgwDynamic.Update();
dgwDynamic.Refresh();
tabControl1.Update();
tabControl1.Refresh();
}
}
}//Using
}//End method ImportExcel

private void dgwDynamic_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
List<String> myList = new List<String>();
myList.Add("Value1");
myList.Add("Value2");
myList.Add("Value3");

TabControl.TabPageCollection pages = tabControl1.TabPages;

foreach (TabPage page in pages)
{
DataGridView grd = page.Controls.OfType<DataGridView>().FirstOrDefault();

foreach (DataGridViewRow row in grd.Rows)
{

foreach (DataGridViewCell cell in row.Cells)
{
if (cell.ColumnIndex == 13) //SET YOUR PARTICULAR COLUMN INDEX HERE!!
{
foreach (string item in myList)
{
if ((string)cell.Value == item)
{
row.DefaultCellStyle.BackColor = Color.Yellow;
}

}//foreach

}//If

}//foreach

}//foreach

}//foreach

}//dgwDynamic_CellFormatting

Continue reading...
 
Back
Top