到目前為止我所做的
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;
}
}
網格視圖

我試圖隱藏Visible列值所在的整個行False
uj5u.com熱心網友回復:
我認為,這里的主要問題是您正在替換Visible行的值,而不是 Datagrid 的行。替換foreach為for:
for(int i=0; i <= dataGridView1.Rows.Count();i ) {
dataGridView1.Rows[i].Visible = Convert.ToBoolean(dataGridView1.Rows[i].Cells[0].Value);
}
dr.Cells[0].Value.ToString()當你得到那一行時,它的價值是多少?使用除錯器和 quickwatch 檢查它。也許不是你展示的“假”。
主要思想是使用 Convert 獲取任何型別的錯誤。而且你根本不需要 if 。
if (Convert.ToBoolean(dr.Cells[0].Value))
{
dr.Visible = false;
}
而且你根本不需要 if 。
dr.Visible = Convert.ToBoolean(dr.Cells[0].Value);
uj5u.com熱心網友回復:
您可以使用DataGridView CellPainting事件。
每次dataGridView1需要重新繪制單元格時,都會觸發該事件。
好訊息是這個事件會在dataGridView1初始化和用戶離開單元格時觸發。因此,此解決方案將在DataGridView初始化時洗掉任意行(然后洗掉第 0 列中帶有“False”的所有加載行),但還會洗掉用戶在運行時更改為“False”的所有行。
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;
}
}
}
在“設計”視圖中的事件串列中添加事件,或將其直接添加到包含控制元件的設計器類中 dataGridView1
//
// dataGridView1
//
...
this.dataGridView1.Name = "dataGridView1";
this.dataGridView1.CellPainting = new System.Windows.Forms.DataGridViewCellPaintingEventHandler(this.dataGridView1_CellPainting);
...
uj5u.com熱心網友回復:
經過一些研究,我相信您最好“過濾”網格DataSource而不是將單個網格行的Visible屬性設定為false.
這樣做的最大問題是……您不能將 gridsCurrentRow Visible屬性設定為false. 這將拋出一個例外,抱怨......
“不能隱藏與貨幣經理職位相關的行”
...基本上這是說網格CurrentRow不能隱形。
考慮到這一點,似乎這種方法可能不起作用,因為網格中至少有一 (1) 行是 ,CurrentRow如果網格的CurrentRow“可見”單元格設定為“假” ,您的代碼將失敗。
此外,為了利用測驗引數……如果所有行都是“假”怎么辦?...在這種情況下,可以保證例外,因為至少有一行是CurrentRow.
希望這可以解釋“為什么”您的代碼在某些時候可以作業而在其他時候不作業。
因此,我建議一個簡單的解決方案,避免使用網格貨幣管理器。這可以通過過濾網格來完成DataSource。類似于下面的按鈕單擊事件……
private void button1_Click(object sender, EventArgs e) {
DataView dv = new DataView(dataSet.Tables[0]);
dv.RowFilter = "Visible = True"; // <- filter rows that have True in the Visible column
dataGridView1.DataSource = dv;
}
不清楚您問題中發布的代碼在“哪里”執行,但是在我上面的解決方案中,如果您創建dataSet或至少創建dataSet.Tables[0]一個“GLOBAL”變數會使事情變得更容易。原因是當您使用DataView.RowFilter然后將網格資料源設定為DataView...然后除非您有權訪問原始表dataset.Tables[0]...您將無法“取消過濾”網格,而是需要重新查詢D B。我希望這是有道理的。祝你好運。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/377587.html
上一篇:計算輸出不正確
下一篇:關閉時防止對話框卸載
