2012-08-15 67 views
0

我是c#程序員。目前,我嘗試在datagrid-viewer中的sql數據中添加5列中的3列(fileId,filePath,authorName,fileContent,DateSend) fileId和fileContent列是隱藏的。非常感謝你!datagridview顯示從sql數據庫中選擇的行?

 con = new SqlConnection("Data Source=LEO-PC\\SQLEXPRESS;Initial Catalog = datashare;Integrated Security = True"); 
     cmd = new SqlCommand("select * from maintable", con); 
     con.Open(); 
     SqlDataReader sqlRead; 
     try 
     { 
      sqlRead = cmd.ExecuteReader(); 
      while (sqlRead.Read()) 
      { 
       //Adding to datagrid 
      } 
     } 
     catch (Exception ex) 
     { 
      MessageBox.Show(ex.Message); 
     } 
     finally 
     { 
      con.Close(); 
     } 
+0

如果你是初學者,你可能會檢查SQLDataSource控件。 http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.sqldatasource.aspx – 2012-08-15 06:30:40

回答

0

要隱藏2個字段在網格中創建一個OnRowCreated事件:

OnRowCreated = 「gridView1_RowCreated」

記住使用

SqlDataReader reader = cmd.ExecuteReader();  
gridView1.DataSource = reader; 
到填充網格

和gridview必須有屬性必須是AutoGeneretedColumns = "true"

然後創建活動如下:

protected void gridView1_RowCreated(object sender, GridViewRowEventArgs e) 
{ 
      if (e.Row.RowType == DataControlRowType.Header) 
      { 
       for (int i = 0; i < e.Row.Cells.Count; i++) 
       { 
        DataControlFieldCell cell = 
         (DataControlFieldCell) e.Row.Cells[i]; 


        if (cell.ContainingField.HeaderText == "fileId") 
        { 
         e.Row.Cells[i].Visible = false; 
         cell.Visible = false; 
        } 

        if (cell.ContainingField.HeaderText == "fileContent") 
        { 
         e.Row.Cells[i].Visible = false; 
         cell.Visible = false; 
        } 
       } 
      } 

      if (e.Row.RowType == DataControlRowType.DataRow) 
      { 
       for (int i = 0; i < e.Row.Cells.Count; i++) 
       { 
        DataControlFieldCell cell = 
         (DataControlFieldCell) e.Row.Cells[i]; 

        if (cell.ContainingField.ToString() == "fileId") 
        { 
         cell.Visible = false; 
        } 

        if (cell.ContainingField.ToString() == "fileContent") 
        { 
         cell.Visible = false; 
        } 
       } 
      } 
} 

這可能不是最effecient方式,但它使用代碼服務宗旨。當列被綁定時,應該能夠使用gridview模板隱藏列。

相關問題