GridView Asp .Net-根据同一列中第一个下拉列表的值更改第二个下拉列表的选定值

时间:2017-02-02 08:54:47

标签: c# asp.net gridview

我是ASP.NET和C#的新手。我有一个带有下拉列表的网格视图。如果网格视图是这样的实例,

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="`server`">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>

    </div>
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1">
            <Columns>
                <asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False" ReadOnly="True" SortExpression="ID" />
                <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
                <asp:BoundField DataField="Designation" HeaderText="Designation" SortExpression="Designation" />
                <asp:TemplateField HeaderText="City">
                    <ItemTemplate>
                        <asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="SqlDataSource2" DataTextField="City" DataValueField="City">
                        </asp:DropDownList>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
        <asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:CS %>" SelectCommand="SELECT [City] FROM [EmployeeDetails]"></asp:SqlDataSource>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:CS %>" SelectCommand="SELECT [ID], [Name], [Designation] FROM [EmployeeDetails]"></asp:SqlDataSource>
    </form>

并且在Column City中,如果我假设我在第一个DropDown中选择了Mumbai,我希望City列中的其他下拉列表自动更改为Mumbai。

怎么做?

1 个答案:

答案 0 :(得分:1)

在您的aspx文件中更改如下,

<asp:DropDownList ID="DropDownList1" runat="server"  DataTextField="City" DataValueField="City" AutoPostBack="true" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">

在你的aspx.cs文件中,

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        DropDownList selectedDropDown = (DropDownList)sender;
        foreach(GridViewRow gRow in GridView1.Rows)
        {
            DropDownList ddlCity = (DropDownList)gRow.FindControl("DropDownList1");
            ddlCity.SelectedValue = selectedDropDown.SelectedValue;
        }
    }

这适用于所有下拉菜单。

如果您希望它仅适用于First Dropdown,请使用以下条件。

if (((GridViewRow)selectedDropDown.Parent.Parent).RowIndex == 0)
        {
            foreach (GridViewRow gRow in GridView1.Rows)
            {
                DropDownList ddlCity = (DropDownList)gRow.FindControl("DropDownList1");
                ddlCity.SelectedValue = selectedDropDown.SelectedValue;
            }
        }