在下拉选择更改时填充Datagrid中的下拉列表

时间:2016-09-07 10:13:15

标签: asp.net vb.net datagrid

我正在使用ASP.Net Webforms应用程序中的Datagrid。根据此处的代码,Datagrid中有两个下拉列表

<asp:DataGrid runat="server" CssClass="tab table table-bordered table-striped table-hover " ID="dgUnsuitableSwitch" AutoGenerateColumns="False">
<Columns>
    <asp:BoundColumn DataField="Fund Name" HeaderText="Fund Name" HeaderStyle-CssClass="centre" ItemStyle-CssClass="centre"></asp:BoundColumn>
    <asp:BoundColumn DataField="Fund Risk Profile" HeaderText="Fund Risk Profile" HeaderStyle-CssClass="centre" ItemStyle-CssClass="centre"></asp:BoundColumn>
    <asp:BoundColumn DataField="Customer Name" HeaderText="Customer Name" HeaderStyle-CssClass="centre" ItemStyle-CssClass="centre"></asp:BoundColumn>
    <asp:BoundColumn DataField="Investment Date" HeaderText="Investment Date" HeaderStyle-CssClass="centre" ItemStyle-CssClass="centre"></asp:BoundColumn>

    <asp:TemplateColumn HeaderText="Switching to Product" HeaderStyle-CssClass="centre" ItemStyle-CssClass="centre">
        <ItemTemplate>
            <asp:DropDownList runat="server" Width="150px" CssClass="centre" ID="ddlProduct">
            </asp:DropDownList>
        </ItemTemplate>
    </asp:TemplateColumn>

    <asp:TemplateColumn HeaderText="Switching to Fund" HeaderStyle-CssClass="centre" ItemStyle-CssClass="centre">
        <ItemTemplate>
            <asp:DropDownList runat="server" Width="150px" CssClass="centre" ID="ddlFund">
            </asp:DropDownList>
        </ItemTemplate>
    </asp:TemplateColumn>

    <asp:TemplateColumn HeaderText="Switching to Amount (£)" HeaderStyle-CssClass="centre" ItemStyle-CssClass="centre">
        <ItemTemplate>
            <asp:TextBox runat="server" CssClass="form-control" placeholder="Amount" Width="50px" ID="txtOtherExistingAmount"></asp:TextBox>
            <ajaxToolkit:FilteredTextBoxExtender ID="filtertxtOtherExistingAmount1" runat="server"
                Enabled="True" TargetControlID="txtOtherExistingAmount" FilterType="Custom" ValidChars=".-0123456789"></ajaxToolkit:FilteredTextBoxExtender>
        </ItemTemplate>
    </asp:TemplateColumn>

    <asp:TemplateColumn HeaderText="Switching to Lump Sum Amount (£)" HeaderStyle-CssClass="centre" ItemStyle-CssClass="centre">
        <ItemTemplate>
            <asp:TextBox runat="server" CssClass="form-control" Width="50px" placeholder="Amount" ID="txtLumpSumAmount"></asp:TextBox>
            <ajaxToolkit:FilteredTextBoxExtender ID="filtertxtLumpSumAmount1" runat="server"
                Enabled="True" TargetControlID="txtLumpSumAmount" FilterType="Custom" ValidChars=".-0123456789"></ajaxToolkit:FilteredTextBoxExtender>
        </ItemTemplate>
    </asp:TemplateColumn>

</Columns>

我能够毫无问题地填充第一个下拉列表,如此

For Each item As DataGridItem In dgUnsuitableSwitch.Items
 Dim ddlProduct As DropDownList = DirectCast(item.FindControl("ddlProduct"), DropDownList)

 With ddlProduct
     .Items.Add("-- Select Product --
     .Items.Add("Premium")
     .Items.Add("Growth")
     .Items.Add("Income")
     .Items.Add("Index"
     .Items.Add("Fixed ")
     .Items.Add("Cash")
 End With

下一步

我遇到的问题是将更改事件绑定到下拉列表但是现在无法使其工作。

我相信我需要广告一个事件处理程序但不确定我需要添加它的位置,或者可能完全错误。

我很高兴听到VB或C#中的答案

感谢

西蒙

2 个答案:

答案 0 :(得分:0)

我认为这样的事情可以解决它吗?

我们通常使用Telerik radgrids,所以我对gridviews不是很熟悉,但我不认为它会有很大不同。

基本上,您首先使用默认值(如果需要/需要)将数据源绑定到网格,然后每当ddl的索引更改时,您调用第一次使用索引值设置数据源的相同函数

然后使用该值过滤或收集新的数据源。

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    Try
        'Bind your grid
        BindGrid() 
    Catch ex As Exception
        'Print any exceptions to your validator
        'Me.CustomValidatorAdditional.ErrorMessage = ex.Message
        'Me.CustomValidatorAdditional.IsValid = False
    End Try
End Sub

Private Sub BindGrid(Optional ByVal Product As String = "premium")
    Try
        dgUnsuitableSwitch.DataSource = GetProducts(Product) 'returns a datasource 
        dgUnsuitableSwitch.DataBind()

    Catch ex As Exception
        Me.CustomValidatorAdditional.ErrorMessage = ex.Message
        Me.CustomValidatorAdditional.IsValid = False

    End Try
End Sub

protected void ddlProduct_SelectedIndexChanged(object sender, EventArgs e)
{
' Set your new datasource / filter on your old. 
' I use Telerik, but it would looks something like this
    bindGrid(e.Value) 'Change the parameter to your choice. 
}

如果您只需要根据主ddl的索引更改其他ddl的内容,那么您的操作方式与我在那里的方式类似,但不是使用数据源绑定网格,而是将ddl绑定到您选择的一组项目会根据条件而变化:

Private Sub changeDdl(Optional ByVal Product As String = "premium")
    Dim ddlFund As DropDownList = DirectCast(item.FindControl("ddlFund"), DropDownList)

    IF (Product = "premium)
       ddlFund.items.add(item) 'Or however the syntax is for a asp-ddl list
                               ' And this continues until you have set your items

   ELSE IF (Product = "Growth")
        ddlFund.items.add(item) 'Or however the syntax is for a asp-ddl list
                                ' And this continues until you have set your items

    'etc etc etc'
End Sub

答案 1 :(得分:0)

使用此JQuery

工作
$(".ddlMoveToProduct").change(function() {
            var fundId = $(this).closest('td').next().find('select').attr("id");

            console.log(fundId);

            var option = $(this).val();
            var params = {
                val: option
            };

            $.ajax({
                type: "POST",
                url: "Default.aspx/SelectMoveToFund",
                data: JSON.stringify(params),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    $('select').select2('destroy');
                    var ddl = $("#" + fundId);

                    ddl.empty().append('<option selected="selected" value="0">Please select</option>');
                    $.each(data.d, function () {
                        ddl.append($("<option></option>").val(this['Value']).html(this['Text']));
                    });
                    $('select').select2();

                },
                error: function (data) {
                    console.log("error :" + data);
                    console.log(data);
                }
            });

        });

然后使用webmethod

<System.Web.Script.Services.ScriptMethod(), _
System.Web.Services.WebMethod()> _
Public Shared Function SelectMoveToFund(val As String) As List(Of ListItem)
    '' will be changing this to an ajax call 

    Dim dt = GetFundsToMoveTo(val)

    Dim retVal = (From row As Object In dt.Rows Select New ListItem() With {
        .Value = row(0),
    .Text = row(0)}).ToList()

    Return retVal

End Function