SearchForKnowledge
SearchForKnowledge

Reputation: 3751

How to update the SQLDataSource of a DropDownList from code-behind

I have two dropdownlists:

<td style="width: 20%;">
    <!-- TASK NAME -->
    <asp:DropDownList ID="ddlTaskName" DataSourceID="dsPopulateTaskName" AutoPostBack="true" DataValueField="Task Name" runat="server" AppendDataBoundItems="true" OnSelectedIndexChanged="ddlTaskName_onSelectIndexChanged">
        <asp:ListItem Text="All" Value="%"></asp:ListItem>
    </asp:DropDownList>
    <asp:SqlDataSource ID="dsPopulateTaskName" runat="server" ConnectionString="<%$ ConnectionStrings:gc %>" SelectCommand=""></asp:SqlDataSource>
</td>
<td style="width: 20%;">
    <!-- SERVICE -->
    <asp:DropDownList ID="ddlService" DataSourceID="dsPopulateService" AutoPostBack="true" DataValueField="Service" runat="server" AppendDataBoundItems="true" OnSelectedIndexChanged="ddlService_onSelectIndexChanged">
        <asp:ListItem Text="All" Value="%"></asp:ListItem>
    </asp:DropDownList>
    <asp:SqlDataSource ID="dsPopulateService" runat="server" ConnectionString="<%$ ConnectionStrings:gc %>" SelectCommand=""></asp:SqlDataSource>
</td>

code-behind on Page_Load:

strForDropDownList = @" FROM [Db].[dbo].[table1] WHERE [stat] = 'A'";
string pol = " AND ";
if (ddlTaskName.SelectedIndex == 0)
{
    pol += " ([tcol] LIKE '%' OR [tcol] IS NULL) AND ";
}
else
{
    pol += " [tcol] = '" + ddlTaskName.SelectedValue.TrimEnd() + "' AND ";
}
if (ddlService.SelectedIndex == 0)
{
    pol += " (scol LIKE '%' OR scol IS NULL) AND ";
}
else
{
    pol += " scol = '" + ddlService.SelectedValue.TrimEnd() + "' AND ";
}
strWhere = pol;
dsPopulateTaskName.SelectCommand = @"SELECT DISTINCT [tcol] 'Task Name'" + strForDropDownList + strWhere;
dsPopulateService.SelectCommand = @"SELECT DISTINCT scol 'Service'" + strForDropDownList + strWhere;

When the page loads, everything starts with % and populates the dropdownlists correctly. If I select an option from the ddlService dropdownlist, the dsPopulateTaskName.SelectCommand displays the correct query to repopulate the ddlTaskName dropdownlist but it doesn't update it.

Please help me resolve it.

Upvotes: 1

Views: 2494

Answers (1)

Nima Derakhshanjan
Nima Derakhshanjan

Reputation: 1404

you should call ddlService.DataBind() and ddlTaskName.DataBind() after setting the SelectCommand , I mean like below :

dsPopulateTaskName.SelectCommand = 
@"SELECT DISTINCT [tcol] 'Task Name'" + strForDropDownList + strWhere;
ddlService.DataBind();

dsPopulateService.SelectCommand = 
@"SELECT DISTINCT scol 'Service'" + strForDropDownList + strWhere;
ddlTaskName.DataBind();

hope it helps

Upvotes: 1

Related Questions