0

我有看似简单但实际上几乎不可能的问题

我有一个数据网格和 sqldatasource。

如果我想选择所有联系人> 1,那么我可以使用如下参数:

Select * from Contacts where ContactID > @Contact 我实际上想从下拉框中选择 3 个可能的值:
> 1
= 0
>= 0

您似乎无法更改 sql 语句或下拉框中要求为整数值的 > = 或 >=。

我不知道该怎么做。有谁能帮忙吗?

4

1 回答 1

0

您必须修改 SqlDataSource 的 SQL 语句来实现这一点,然后重新绑定 DataGrid 中的数据。您可以通过处理SelectedIndexChangedDropDown 上的方法和AutoPostBack="true"/或使用按钮来执行此操作。

假设您的标记类似于以下内容(根据需要删除 OnSelectedIndexChanged 和 AutoPostBack 属性或按钮):

<asp:SqlDataSource runat="server" ID="dsContacts" ConnectionString="<%$ ConnectionStrings:MyConnectionString %>" SelectCommand="SELECT * FROM Contacts WHERE ContactID > @Contact" />
<asp:DataGrid runat="server" ID="dgContacts" DataSourceID="dsContacts" />
<asp:DropDownList runat="server" ID="ddlWhereOptions" AutoPostBack="true" OnSelectedIndexChanged="ddlWhereOptions_SelectedIndexChanged">
    <asp:ListItem Text="> 1" />
    <asp:ListItem Text="= 0" />
    <asp:ListItem Text=">= 0" />
</asp:DropDownList>
<asp:Button runat="server" ID="btnChangeQuery" OnClick="btnChangeQuery_Click" />

然后你的代码隐藏可能看起来像这样:

Protected Sub ddlWhereOptions_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ddlWhereOptions.SelectedIndexChanged 'add handles clause just in case eventwireup is false

    ChangeQuery()    

End Sub

Protected Sub btnChangeQuery_Click(sender As Object, e As EventArgs) Handles btnChangeQuery.Click 'add handles clause just in case eventwireup is false

    ChangeQuery()    

End Sub

Private Sub ChangeQuery()

    'set up some variables instead of building a new string in every case
    Dim whereOperator As String = ""
    Dim whereValue As Integer = 0

    Select Case ddlWhereOptions.SelectedItem.Text

        Case "> 1"
            whereOperator = ">"
            whereValue = 1

        Case "= 0"
            whereOperator = "="
            whereValue = 0

        Case ">= 0"
            whereOperator = ">="
            whereValue = 0

    End Select

    'change the select command on the datasource, clear any existing parameters and add the new one with the correct value
    dsContacts.SelectCommand.CommandText = "SELECT * FROM Contacts WHERE ContactID " & whereOperator & " @Contact"
    dsContacts.SelectCommand.Parameters.Clear()
    dsContacts.SelectCommand.Parameters.AddWithValue("@Contact", whereValue)

    're-bind the data grid
    dgContacts.DataBind()

End Sub
于 2013-06-06T10:58:27.493 回答