2017-06-21 72 views
0

我正試圖編寫一個項目來顯示MMABooks數據庫中的2個表的一些數據。這些代碼在C#中工作,但它們不能在ASP.Net中工作。其實,它什麼都不做,我也沒有任何錯誤!爲什麼?問題是什麼?爲什麼我的ASP.NET項目不做任何事情?

string connectionString = "Data Source=localhost\\SqlExpress;" + 
       "Initial Catalog=MMABooks;Integrated Security=True"; 

SqlConnection connection = new SqlConnection(connectionString); 
string selectStatement = "SELECT Customers.Name, Customers.City, States.StateName " + 
       "FROM Customers " + 
       "INNER JOIN States " + 
       "ON Customers.State = States.StateCode " + 
       "WHERE Name LIKE @Name"; 

SqlCommand SelectCommand = new SqlCommand(selectStatement, connection); 
SelectCommand.Parameters.AddWithValue("@Name", TextBox1.Text.Trim() + "%"); 

connection.Open(); 
    var dataAdapter = new SqlDataAdapter(SelectCommand); 
    DataTable dt = new DataTable(); 
    dataAdapter.Fill(dt); 
    GridView1.DataSource = dt; 

回答

3

您需要GridView1.DataBind()其中綁定的最後一行後的數據源到GridView的ASP.NET。

GridView1.DataSource = dt; 
GridView1.DataBind(); 
0

你缺少GridView1.DataSource = dt;GridView1.DataSource = dt;

string connectionString = "Data Source=localhost\\SqlExpress;" + 
       "Initial Catalog=MMABooks;Integrated Security=True"; 

SqlConnection connection = new SqlConnection(connectionString); 
string selectStatement = "SELECT Customers.Name, Customers.City, States.StateName " + 
       "FROM Customers " + 
       "INNER JOIN States " + 
       "ON Customers.State = States.StateCode " + 
       "WHERE Name LIKE @Name"; 

SqlCommand SelectCommand = new SqlCommand(selectStatement, connection); 
SelectCommand.Parameters.AddWithValue("@Name", TextBox1.Text.Trim() + "%"); 

connection.Open(); 
    var dataAdapter = new SqlDataAdapter(SelectCommand); 
    DataTable dt = new DataTable(); 
    dataAdapter.Fill(dt); 
    GridView1.DataSource = dt; 
    GridView1.DataBind();//you are missing this 
相關問題