2017-06-14 130 views
2

我有一個GridView。我正在嘗試使用DataTable將數據庫表格數據顯示到網格中。因此,我將查詢結果保存在DataTable中,但數據未顯示。這是我的代碼。請幫忙。在c#數據表中顯示數據庫表數據,但數據表爲空

protected void Page_Load(object sender, EventArgs e) 
{ 
    if (!IsPostBack) 
    {   
     DataTable dataTable = new DataTable(); 
     string constr = ConfigurationManager.ConnectionStrings["gridconnection"].ConnectionString; 

     string query = "select * from GridExcel"; 

     SqlConnection con1 = new SqlConnection(constr); 
     SqlCommand cmd = new SqlCommand(query, con1); 
     con1.Open(); 

     // create data adapter 
     SqlDataAdapter da = new SqlDataAdapter(cmd); 
     // this will query your database and return the result to your 
     datatable 
     da.Fill(dataTable); 
     Gridview1.DataSource = dataTable; 
     Gridview1.DataBind(); 
     ViewState["CurrentTable"] = dataTable; 
     con1.Close(); 
    } 
} 
+1

con.Open();或con1.Open()? –

+0

從GridExcel中選擇*是否返回任何內容? –

+0

'SqlDataAdapter'不需要打開連接 –

回答

0

嘗試使用DataReader:

protected void Page_Load(object sender, EventArgs e) 
{ 
    if (!IsPostBack) 
    { 

    DataTable dataTable = new DataTable(); 
    string constr =  ConfigurationManager.ConnectionStrings["gridconnection"].ConnectionString; 

    string query = "select * from GridExcel"; 

    SqlConnection con1 = new SqlConnection(constr); 
    SqlCommand cmd = new SqlCommand(query, con1); 
    con1.Open(); 

    // create data adapter 
    SqlDataReader reader = cmd.ExecuteReader(); 
    // this will query your database and return the result to your datatable 
    dataTable.Load(reader); 
    Gridview1.DataSource = dataTable; 
    Gridview1.DataBind(); 
    ViewState["CurrentTable"] = dataTable; 
    con1.Close(); 
    } 
} 
+0

沒有人要求我在那裏解釋/澄清,在這裏我感到懷疑爲什麼讀者在適配器失敗的地方做這項工作,這就是我要求澄清的原因。如果您需要澄清我的任何職位手段費用,可以通過評論或通過郵件進行諮詢。 –

+0

我對論據不感興趣,並且採取個人報復,好心地忽略我的評論(讓我也刪除它)。對不起,浪費時間 –

+0

澄清:據我所知,SqlDataAdapter填充一個表,如果列已經在那裏存在(https://msdn.microsoft.com/de-de/library/905keexk(v=vs.110) ).aspx) –

0

下面的代碼對我的作品。

string constring = @"Data Source=.\SQL2005;Initial Catalog=gridconnection;"; 
    using (SqlConnection con = new SqlConnection(constring)) 
    { 
     using (SqlCommand cmd = new SqlCommand("select * from GridExcel", con)) 
     { 
      cmd.CommandType = CommandType.Text; 
      using (SqlDataAdapter da = new SqlDataAdapter(cmd)) 
      { 
       using (DataTable dt = new DataTable()) 
       { 
        da.Fill(dt); 
        dataGridView1.DataSource = dt; 
       } 
      } 
     } 
    }