2013-03-03 27 views
0

我試圖創建自己的命令來提取數據。 第一即時通訊作出的.aspx從工具箱中的SqlDataSource:GridView和SqlDataSource

<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
     onselecting="SqlDataSource2_Selecting"></asp:SqlDataSource> 

然後添加GridView控件:

<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
     onselecting="SqlDataSource1_Selecting"></asp:SqlDataSource> 

,現在我想我自己寫的查詢,所以我就雙擊「的SqlDataSource」>進入的.aspx .cs:

protected void SqlDataSource1_Selecting(object sender, SqlDataSourceSelectingEventArgs e)  
{ 
    SqlDataSource1.SelectCommand = "SELECT name, num FROM Table WHERE [email protected]"; 
} 

問題在哪裏?當我運行這個應用程序不工作。

回答

0

有幾個問題。 第一個是你使用了參數化查詢,但沒有定義你的參數是什麼。 第二個是你只是分配一個SQL查詢到你的SqlDataSource1,但你沒有說這樣做。

protected void Page_Load(object sender, EventArgs e) 
{ 
    System.Data.Sql.SqlConnection conn= new System.Data.Sql.SqlConnection(/*your connection string comes here*/); 

    string query= "SELECT name, num FROM Table WHERE [email protected]"; 

    System.Data.DataTable dt = new System.Data.DataTable(); 
    System.Data.Sql.SqlCommand cmd = new System.Data.Sql.SqlCommand(query, conn); 

    System.Data.Sql.SqlDataAdapter da1 = new System.Data.Sql.SqlDataAdapter(cmd); 
    da1.SelectCommand.Parameters.AddWithValue("@MyString", your_string); 

    da1.Fill(dt); 

     if (dt.Rows.Count > 0) 
     { 
      GridView1.DataSource = dt; 
      GridView1.DataBind(); 
     } 
    } 
+0

訪問http://www.connectionstrings.com爲您的連接字符串。 – zkanoca 2013-03-03 17:53:28

+0

我試圖做這樣的事情和錯誤: 「數據控件'GridView1'上的數據屬性,如DataSource,DataSourceID和DataMember無法在控件的數據綁定階段進行更改。」在「GridView1.DataSource = dt;」 – iTuj 2013-03-03 18:46:31

+0

然後將上面的代碼寫入Page_Load()方法 – zkanoca 2013-03-03 18:47:56

0

您沒有設置SqlDataSource1的參數。
和我不能連接字符串。

0

您應該添加選擇參數與SELECT命令

 
protected void SqlDataSource1_Selecting(object sender, SqlDataSourceSelectingEventArgs e) 
     { 
      SqlDataSource1.SelectCommand = "SELECT name, num FROM Table WHERE [email protected]"; 
SelectParameters["MyString"].DefaultValue = "Your Parameter here"; 

     } 
相關問題