What I've done so far
DataSet dataSet = new DataSet();
dataSet.ReadXml(dialog.FileName);
dataGridView1.DataSource = dataSet.Tables[0];
MessageBox.Show(this.dataGridView1.Columns["Visible"].Index.ToString());//To hide -returns 0
foreach (DataGridViewRow dr in dataGridView1.Rows)
{
if (dr.Cells[0].Value.ToString() == "False")
{
dr.Visible = false;
}
}
I'm trying to hide the entire Row where the Visible
Column value is False
CodePudding user response:
The main problem here, I think, is that you are replacing the Visible
value of the row, instead of the row of the Datagrid. Replace the foreach
with a for
:
for(int i=0; i <= dataGridView1.Rows.Count();i ) {
dataGridView1.Rows[i].Visible = Convert.ToBoolean(dataGridView1.Rows[i].Cells[0].Value);
}
What is the value of dr.Cells[0].Value.ToString()
when you get that row? Check it with debugger and quickwatch. Maybe is not "False" as you show it.
The main idea is get any kind of false with Convert. And also you don't need the if at all.
if (Convert.ToBoolean(dr.Cells[0].Value))
{
dr.Visible = false;
}
And also you don't need the if at all.
dr.Visible = Convert.ToBoolean(dr.Cells[0].Value);
CodePudding user response:
You may use the DataGridView
CellPainting event.
Everytime a cell in dataGridView1
needs repainting the event is fired.
The good thing is that this event will fire when the dataGridView1
is initialized and when the user leaves a cell. Hence this solution will remove the arbitrary rows when the DataGridView
is initializing (and then remove any loaded rows with "False" in column 0) but also remove any rows that are changed to "False" by the user during run time.
private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
if (e.ColumnIndex < 0 || e.RowIndex < 0)
return;
if (dataGridView1.Rows[e.RowIndex].Cells[0].Value == null) //Return if cell value is null
return;
if (e.ColumnIndex == 0) //Current cell to paint is in visible column
{
DataGridViewRow currentRow = dataGridView1.Rows[e.RowIndex]; //Row of current cell
if (currentRow.Cells[0].Value.ToString() == "False")
{
currentRow.Visible = false;
}
}
}
Either add the event at the events list in the Design view or add it directly to the designer class for the control containing dataGridView1
//
// dataGridView1
//
...
this.dataGridView1.Name = "dataGridView1";
this.dataGridView1.CellPainting = new System.Windows.Forms.DataGridViewCellPaintingEventHandler(this.dataGridView1_CellPainting);
...