2015-07-19 63 views
0

在以下asp c#代碼中,我試圖使用SqlDataReader顯示數據庫表的內容,但它不工作。此代碼僅處理按鈕單擊事件。我怎樣才能使它工作?爲什麼這段代碼沒有在瀏覽器中顯示錶格?

protected void Button2_Click(object sender, EventArgs e) 
    { 
     GridView1.DataSource = null; 
     GridView1.DataBind(); 
     string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString; 
     using (con) 
     { 
      con.ConnectionString = CS; 
      DataTable dTbl = new DataTable(); 
      dTbl.Columns.Add("ID"); 
      dTbl.Columns.Add("Name"); 
      dTbl.Columns.Add("Salary"); 
      SqlCommand vmd = new SqlCommand(); 
      vmd.Connection = con; 
      vmd.CommandText = "select * from [dbo].[employee]"; 
      con.Open(); 
      SqlDataReader dr = vmd.ExecuteReader(); 
      while (dr.Read()) 
      { 
       DataRow dRow = dTbl.NewRow(); 
       dRow["ID"] = dr[0]; 
       dRow["Name"] = dr[1]; 
       dRow["Salary"] = dr[2]; 
       dTbl.Rows.Add(dRow); 
      } 
     } 
    } 

回答

2

while代碼塊添加

GridView1.DataSource = dTbl; 
GridView1.DataBind(); 

,並從你的代碼開始刪除GridView1.DataBind();

1

你不需要這條線。從你的代碼的開頭刪除它:

GridView1.DataBind();//Remove 

,然後將這兩行之後While循環:

GridView1.DataSource = dTbl; 
GridView1.DataBind(); 

編輯:您也可以做到這一點更簡單的是這樣的:

string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString; 
using (SqlConnection con = new SqlConnection(CS)) 
{ 
     try 
     { 
      con.Open(); 
      SqlCommand command = new SqlCommand("select * from [dbo].[employee]", con); 
      SqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection); 
      GridView1.DataSource = reader; 
      GridView1.DataBind(); 
     } 
     catch 
     { 
     //Handle error 
     } 
} 
相關問題