SqlDataSource 中 參數動態賦值的方法

來源:互聯網
上載者:User

第一種情況:查詢條件是固定的

下面以SelectCommand為例進行說明
建立的SqlDataSource如下:

 <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:WHGDTempConnectionString %>"
            SelectCommand="SELECT [ID], [TVNum], [HostName], [TerminalNum], [Addr] FROM [AddrInfo] WHERE ([ID] = @ID)">
            <SelectParameters>
                <asp:Parameter DefaultValue="1" Name="ID" Type="Decimal" />
            </SelectParameters>
        </asp:SqlDataSource>

在程式中運行時給ID參數賦值如下:
this.SqlDataSource1.SelectParameters["ID"].DefaultValue = "2";//這個就是給參數的指派陳述式
 this.SqlDataSource1.DataBind();
 this.GridView1.DataBind();

 

第二種情況:查詢條件是隨機變化的,動態增減;這時需要在後台構造Sqldatasource的selectcommand。這種情況下需要如下操作:

        第一步:清空SqlDataSource的SelectParameters

this.SqlDataSource1.SelectParameters.Clear();

       第二步:構造SelectCommand,並給selectparameters增加參數並賦值

 

string Sqlstr = "SELECT * FROM [butabel] WHERE ";
 if (TextBox2.Text != "" && TextBox2.Text.Trim() != "")
    {
       Sqlstr = Sqlstr + " ([circuitvB] LIKE '%' + @circuitvB + '%') and ";
    //下面這是給Sqldatasource增加 SelectParameters參數並賦值       this.SqlDataSource1.SelectParameters.Add("circuitvB", System.TypeCode.String, TextBox2.Text.Trim());
        }

   後記:如果涉及到Gridview的分頁、排序、編輯需要給相應的函數中添加查詢函數。例如:

           protected void GridView1_PageIndexChanging1(object sender, GridViewPageEventArgs e) { searchFuc(); }

           protected void GridView1_Sorting(object sender, GridViewSortEventArgs e) { searchFuc();}

           protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e) {  searchFuc();}

           protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e) { searchFuc();}

           protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)  {searchFuc();}
           protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) { searchFuc(); }

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.