在 gridview 中,每行都有 2 个下拉菜单。选择第一个下拉列表中的值后,它应该在第二个下拉列表中显示下拉值

问题描述 投票:0回答:1

gridview 中的下拉菜单依赖于另一个下拉菜单。

 here is what  i tried

aspx

选择程序

            </asp:DropDownList>
            <asp:RequiredFieldValidator ID="rfvddlProgram" runat="server" ErrorMessage="*" ControlToValidate="ddlProgram" Font-Bold="False" Font-Names="Verdana" Font-Size="8pt"
                SetFocusOnError="True" ValidationGroup="v1" ForeColor="Red" InitialValue="0"></asp:RequiredFieldValidator>
            <%--  <a href="#" target="_blank">BA Economics</a>--%>
        </ItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField HeaderText="Location">
        <ItemTemplate>
            <asp:DropDownList ID="ddl_Location" runat="server" class="form-control form-control-sm  mb-9">
                <asp:ListItem Value="0">Select Location</asp:ListItem>

            </asp:DropDownList>
            <asp:RequiredFieldValidator ID="rfvddlLocation" runat="server" ErrorMessage="*" ControlToValidate="ddl_Location" Font-Bold="False" Font-Names="Verdana" Font-Size="8pt"
                SetFocusOnError="True" ValidationGroup="v1" ForeColor="Red" InitialValue="0"></asp:RequiredFieldValidator>
        </ItemTemplate>
    </asp:TemplateField>
</Columns>
<FooterStyle BackColor="White" ForeColor="#000066" />
<HeaderStyle BackColor="#6777ef" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" />
<RowStyle ForeColor="#000066" />
<SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#007DBB" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#00547E" />





code behind file

 protected void gvProgram_RowDataBound(object sender, GridViewRowEventArgs e)
 {
     DataSet ds = new DataSet();
     Btech.Mode = "BindData";
     ds = objDal.Adm(Btech);

     if (e.Row.RowType == DataControlRowType.DataRow)
     {
         if (ds.Tables[0].Rows.Count > 0 && ds.Tables[1].Rows.Count > 0)
         {
             DropDownList ddlProgram = (DropDownList)e.Row.FindControl("ddlProgram");
             ddlProgram.Items.Clear();
             ddlProgram.DataSource = ds.Tables[13];
             ddlProgram.DataTextField = "Description";
             ddlProgram.DataValueField = "CourseID";
             ddlProgram.DataBind();
             ddlProgram.Items.Insert(0, new ListItem("Select course", "0"));


             DropDownList ddl_Location = (DropDownList)e.Row.FindControl("ddl_Location");
             //ddlTeacherNames.Items.Clear();
             ddl_Location.DataSource = ds.Tables[14];
             ddl_Location.DataTextField = "CenterName";
             ddl_Location.DataValueField = "CentreCode";
             ddl_Location.DataBind();
             ddl_Location.Items.Insert(0, new ListItem("Select Location", "0"));
         }
     }

 }
 

protected void ddlProgram_SelectedIndexChanged(对象发送者,EventArgs e) {

}

asp.net gridview drop-down-menu dropdown populate
1个回答
0
投票

好吧,有几件事我们必须处理。

首先,加载 GridView。

然后我们必须加载 2 个组合框,但还要为 2 个组合框设置正确的级联值。然后我们必须根据行数据源设置组合框的正确值。所以,理论上这里有 3 个步骤。这一步有点倒退,因为第二个组合框选择和值必须在第一个组合框中设置正确的值。

然后,完成上述所有操作后,我们需要将组合框设置为在用户选择第一个组合框时正确级联,并级联到该 GridRow 中的第二个组合框。

通常,这表明第一个组合框未绑定到给定行中的任何数据,但只有第二个组合框要绑定到给定行数据。

我没有你的样本数据,但让我们假设一些人,我们选择城市,然后第二个级联组合框是他们选择的酒店。

所以,首先是我们的 GridView 标记:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
    DataKeyNames="ID" 
    CssClass="table"
    Width="30%" OnRowDataBound="GridView1_RowDataBound">

    <Columns>
        <asp:BoundField DataField="Firstname" HeaderText="Firstname" />
        <asp:BoundField DataField="LastName" HeaderText="LastName"  />
        <asp:TemplateField HeaderText="Select Hotel City">
            <ItemTemplate>
                <asp:DropDownList ID="cboCity" runat="server" Width="120px"  Height="26px"
                    DataTextField = "City"
                    DataValueField = "City"
                    AutoPostback="true" 
                    OnSelectedIndexChanged="cboCity_SelectedIndexChanged"
                    > 
                </asp:DropDownList>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Select Hotel">
            <ItemTemplate>
                <asp:DropDownList ID="cboHotels" runat="server" Width="210px"  Height="26px"
                    DataValueField ="ID"
                    DataTextField ="HotelName">
                </asp:DropDownList>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

我还要指出,我不关心 GridView 事件,我建议您也不要打扰。

所以,首先是加载组合框的代码。

    DataTable rstCity = new DataTable();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            LoadGrid();
    }

    void LoadGrid ()
    {
        // load up City list for combo box - all rows (scope = page)
        SqlCommand cmdSQL = new SqlCommand("SELECT City from City ORDER BY City");
        rstCity = MyRstP(cmdSQL);

        // load up the grid
        cmdSQL.CommandText = "SELECT * from People ORDER BY FirstName"; 
        GridView1.DataSource = MyRstP(cmdSQL);
        GridView1.DataBind();
    }

好的,上面加载了 GridView。

但是,如上所述,虽然我们有 2 个组合框(选择城市,然后在给定城市列表中选择一家酒店),但只需要保存第二个组合框选择。

因此,在行数据绑定中,我们不仅要加载2个组合框,还要正确设置城市选择,然后根据该酒店加载酒店,然后选择酒店。

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            DataRowView gData = (DataRowView)e.Row.DataItem; // get the row data
            // load the city combo box
            DropDownList cboCity = (DropDownList)e.Row.FindControl("cboCity");
            cboCity.DataSource = rstCity;
            cboCity.DataBind();
            // add blank row for city
            cboCity.Items.Insert(0, new ListItem("Select City", ""));

            // We have to check if a hotel been selected.

            SqlCommand cmdSQL = new SqlCommand();
            DropDownList cboHotels = (DropDownList)e.Row.FindControl("cboHotels");
            Debug.Print($"<{gData["Hotel_ID"].ToString()}>");
            if (gData["Hotel_ID"] != DBNull.Value) {
                cmdSQL = new SqlCommand("SELECT ID, City, HotelName FROM tblHotels WHERE ID = @ID");
                cmdSQL.Parameters.Add("@ID", SqlDbType.Int).Value = gData["Hotel_ID"];
                DataRow OneHotel = MyRstP(cmdSQL).Rows[0];

                // now load Hotel combo box - but cascade from above City cbo
                string strSQL = @"Select ID, HotelName From tblHotels WHERE City = @City " +
                                " ORDER BY HotelName";
                cmdSQL = new SqlCommand(strSQL);
                cmdSQL.Parameters.Add("@City", SqlDbType.NVarChar).Value = OneHotel["City"];

                DataTable rstHotels = MyRstP(cmdSQL);
                cboHotels.DataSource = rstHotels;
                cboHotels.DataBind();
                cboHotels.Items.Insert(0, new ListItem("Select Hotel", ""));
                // set hotels combo to current selected
                cboHotels.SelectedValue = gData["Hotel_id"].ToString();

                // set City combo box to current selected City
                cboCity.SelectedValue = OneHotel["City"].ToString();
            }
        }
    }

所以,上面设置了一切。

接下来是城市选择的级联。因此,请注意上面的组合框的标记是这样的:

 <asp:TemplateField HeaderText="Select Hotel City">
     <ItemTemplate>
         <asp:DropDownList ID="cboCity" runat="server" Width="120px"  Height="26px"
             DataTextField = "City"
             DataValueField = "City"
             AutoPostback="true" 
             OnSelectedIndexChanged="cboCity_SelectedIndexChanged"
             > 
         </asp:DropDownList>
     </ItemTemplate>
   

注意 autopost back = true 的情况。并记下组合框的事件设置。

所以,城市组合框更改事件是这样的:

    protected void cboCity_SelectedIndexChanged(object sender, EventArgs e)
    {
        // city changed, so cascade Hotel cbo
        DropDownList cboCity = (DropDownList)sender;
        GridViewRow gRow = (GridViewRow)cboCity.NamingContainer;
        // filter hotels to current city
        string strCity = cboCity.SelectedItem.Text;
        DropDownList cboHotels = (DropDownList)gRow.FindControl("cboHotels");
        if (strCity != "Select City")
        {
            SqlCommand cmdSQL = new 
                SqlCommand(@"SELECT * from tblHotels WHERE City  = @City ORDER BY HotelName");
            cmdSQL.Parameters.Add("@City", SqlDbType.NVarChar).Value = strCity;                
            cboHotels.DataSource = MyRstP(cmdSQL);
            cboHotels.DataBind();
            cboHotels.Items.Insert(0, new ListItem("Select Hotel", ""));
        }
    }

当然,用户进行更改后,我们需要保存更改。所以,我们的保存按钮是这样的:

    protected void cmdSave_Click(object sender, EventArgs e)
    {
        foreach(GridViewRow gRow in GridView1.Rows)
        {
            DropDownList cboHotel = (DropDownList)gRow.FindControl("cboHotels");
            if (cboHotel.SelectedIndex > 0) 
                rstGrid.Rows[gRow.RowIndex]["Hotel_id"] = cboHotel.SelectedItem.Value;
        }

        using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
        {
            string strSQL = "SELECT * FROM People ORDER BY FirstName,ID";
            using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
            {
                conn.Open();
                SqlDataAdapter da = new SqlDataAdapter(cmdSQL);
                SqlCommandBuilder dau = new SqlCommandBuilder(da);
                da.Update(rstGrid);
            }
        }
    }

结果是这样的:

所以,结果看起来像这样:

© www.soinside.com 2019 - 2024. All rights reserved.