2014-11-08 81 views
1

我需要一些幫助,因爲我一直在嘗試不同的事情,但似乎沒有任何工作正常問題本身就是下面的問題。ASP.NET本地SQL Server數據庫C#gridview數據綁定Visual Studio 2013

如何使用C#背後的代碼將數據綁定到Visual Studio 2013中的網格視圖與本地SQL Server數據庫?

這裏是C#我想:

protected void Page_Load(object sender, EventArgs e) 
{ 
    SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Guillermo\Desktop\HorsensHospital\App_Data\HospitalDB.mdf;Integrated Security=True;Connect Timeout=30"); 
    con.Open(); 

    SqlCommand cmd = new SqlCommand("SELECT [Task_temp_name], [Task_templatesID] FROM [Task_templates]", con); 

    SqlDataAdapter sda = new SqlDataAdapter(cmd); 
    DataSet ds = new DataSet(); 

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

    cmd.ExecuteNonQuery(); 

    con.Close(); 
} 
+0

你得到任何錯誤 – 2014-11-08 12:46:34

回答

0

你已經錯過了Fill方法來填補你的數據集,這就是爲什麼我認爲你是不能夠顯示gridview

填充方法很Improtant方法Bcoz無論你的查詢返回了應該被填充到數據集&那麼該數據集是由您Gridiview 希望綁定,這將幫助你

protected void Page_Load(object sender, EventArgs e) 
{ 
     SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Guillermo\Desktop\HorsensHospital\App_Data\HospitalDB.mdf;Integrated Security=True;Connect Timeout=30"); 
     con.Open(); 
     SqlCommand cmd = new SqlCommand("SELECT [Task_temp_name], [Task_templatesID] FROM [Task_templates]", con); 
     SqlDataAdapter sda = new SqlDataAdapter(cmd); 
     DataSet ds = new DataSet(); 
     sda.Fill(ds); 
     GridView1.DataSource = ds; 
     GridView1.DataBind(); 
     cmd.ExecuteNonQuery(); 
     con.Close(); 

}

注意:您需要在Web.Config中創建連接字符串。 Bcoz如果你在那裏創建了連接字符串,那麼你不需要再創建它。一旦創建有你只需要調用從Web.config

SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionStringNameFromWebConfig"].ConnectionString); 

這是語法調用從web.config中的連接字符串

+0

有你的問題解決了? @Guillermo – 2014-11-08 13:45:07

0

你應該使用的語句是這樣的: 當您使用的SqlDataAdapter你應該填充補法 然後設置DataSource屬性中的GridView

SqlCommand cmd = new SqlCommand("SELECT [Task_temp_name], [Task_templatesID] FROM  [Task_templates]", con); 
    SqlDataAdapter sda = new SqlDataAdapter(cmd); 
    DataTable dt = new DataTable(); 
    sda.Fill(dt); 
    GridView1.DataSource = dt; 
    GridView1.DataBind(); 
    con.Close(); 
1

你剛纔assing你的空DataSet您的Gr的數據集idview的DataSource

您需要使用.Fill method fo填寫您的DataSetSqlDataAdapter。您不需要使用ExecuteNonQuery。這個方法只是執行你的查詢。它不會返回任何數據或結果。

還使用using statement來處置您的SqlConnection,SqlCommandSqlDataAdapter。在使用數據庫連接和對象時,不需要使用.Close()

using(SqlConnection con = new SqlConnection(conString)) 
using(SqlCommand cmd = con.CreateCommand()) 
{ 
    cmd.CommandText = "SELECT [Task_temp_name], [Task_templatesID] FROM [Task_templates]"; 
    using(SqlDataAdapter sda = new SqlDataAdapter(cmd)) 
    { 
     DataSet ds = new DataSet(); 
     sda.Fill(ds); 
     GridView1.DataSource = ds; 
     GridView1.DataBind(); 
    } 
} 
相關問題