2015-02-05 54 views
0

我使用LINQ查询喂GridView控件下方的一个:如何隐藏在GridView asp.net空列动态

var query = (from p in db.Mytable Where     
p.Circuit_Type.Equals(drpCircuitType.SelectedItem) 
&& p.Voltage >= double.Parse(Voltage) 
&& p.HP >= double.Parse(HP) 
select new 
    { 
     p.Circuit_Type, 
     p.Device1_Part_Number, 
     p.Device1_Description, 
     p.Device2_Part_Number, 
     p.Device2_Description, 
     p.Device3_Part_Number, 
     p.Device4_Part_Number, 
     p.Device4_Description, 
     p.Min_Encl_Volume, 
     p.Conditions_of_Acceptability, 
     p.SCCR, 
     p.Voltage_CombinationSCCR, 
     p.U_Reference, 
     p.Combination_Reference 

    }); 
GridTest.DataSource = query; 
GridTest.DataBind(); 

这是工作至今。

所以我想是如果这些的字段为空不显示在GridView的列(自动隐藏)

+0

出100条记录1具有想要隐藏的所有记录整个列没有Device2_Part_Number?或者你想隐藏行吗? – Marco 2015-02-05 13:59:23

回答

0

你需要找到空单元格和隐藏列。这是一个扩展方法。

public static class Extensions 
    { 
     public static DataGridView RemoveEmptyColumns(this DataGridView grdView) 
     { 
      foreach (DataGridViewColumn clm in grdView.Columns) 
      { 
       bool isEmpty = true; 

       foreach (DataGridViewRow row in grdView.Rows) 
       { 
        if (! string.IsNullOrEmpty(row.Cells[clm.Index].Value.ToString())) 
        { 
         isEmpty = false; 
         break; 
        }     
       } 
        grdView.Columns[clm.Index].Visible = isEmpty; 
      } 

      return grdView; 
     } 
    } 

,您可以通过

GridTest.RemoveEmptyColumns(); 

HTH

0

这取决于调用它。 (A)的空字段对于所有行是空的还是(B)对于某些行是空的。

另外,在你的GridView中,你使用自动生成的列还是你手动指定它们?

为了正常工作,它必须是场景A,然后您可以使用RowCreated事件来搜索并隐藏没有要显示数据的列。

+0

对于所有行(A)空字段都将为空,整列必须为空,并且正在使用“自动生成列”。你能用代码解释我该怎么做 – 2015-02-05 15:01:47

0

使用网格的RowDataBound事件。在那里抓取记录,你会检查,如果你想它不显示,然后使用

e.Row.Cells[index].Visible = false; 

其中索引是列索引。

0

好吧,假设所得到的一组数据将返回一个完全相同字段的所有项缺失值,并且所述数据集绑定到带有自动生成列的gridview然后以下工作(在我的计算机上最少)

protected void gvproducts_DataBound(object sender, EventArgs e) 
{ 
    GridView gv = (GridView)sender; 

    // iterate through the gridview's rows and hide emty cells. 
    for (int r = 0; r < gv.Rows.Count; r++) 
    {    
     // only interested in data rows 
     if (gv.Rows[r].RowType == DataControlRowType.DataRow) 
     { 
      // iterate through cells 
      for (int c = 0; c < gv.Rows[r].Cells.Count; c++) 
      { 
       // check text content of cell 
       if (string.IsNullOrEmpty(Server.HtmlDecode(gv.Rows[r].Cells[c].Text).Trim())) 
       { 
        // hide cell 
        gv.Rows[r].Cells[c].Visible = false; 

        // also hide header row's corresponding cell 
        gv.HeaderRow.Cells[c].Visible = false; 
       } 
      } 
     } 
    }  
} 

如果上述假设不成立,您将会看到一个非常奇怪的DataGrid。

你知道他们说什么的假设......