GridView中的ASP.NET下拉列表不断清理

时间:2016-09-07 09:22:03

标签: c# asp.net dropdown

我在网格视图中有2个下拉列表。选择第一个(EqpCatDDL)将确定将填充第二个(DescripDDL)的值。

但是,每次单击Add New Row按钮时,DescripDDL下拉列表都会清除。我不知道为什么会这样。以下是代码:

ASPX:

<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
            <asp:UpdatePanel runat="server">
                <ContentTemplate>
                    <asp:GridView ID="Gridview1" runat="server" ShowFooter="True" AutoGenerateColumns="False"
                        OnRowDataBound="Gridview1_RowDataBound">
                        <Columns>
                            <asp:BoundField DataField="S/N" HeaderText="S/N" />
                            <asp:TemplateField HeaderText="Item Name">
                                <ItemTemplate>
                                    <asp:DropDownList ID="EqpCatDDL" runat="server" AutoPostBack="true" OnSelectedIndexChanged="EqpCatDDL_SelectedIndexChanged">
                                    </asp:DropDownList>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="Description">
                                <ItemTemplate>
                                    <asp:DropDownList ID="DescripDDL" runat="server" AutoPostBack="true">
                                    </asp:DropDownList>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="Quantity">
                                <ItemTemplate>
                                    <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="Remarks">
                                <ItemTemplate>
                                    <asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
                                </ItemTemplate>
                                <FooterStyle HorizontalAlign="Right" />
                                <FooterTemplate>
                                    <contenttemplate>
                                    <asp:Button ID="ButtonAdd" onclick="ButtonAdd_Click" runat="server" Text="Add New Row" />  
                                </contenttemplate>
                                </FooterTemplate>
                            </asp:TemplateField>
                        </Columns>
                    </asp:GridView>
                </ContentTemplate>
            </asp:UpdatePanel>

C#:

    protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        SetInitialRow(); //create a datatable to bind to GridView
    }
}
private void SetInitialRow()
{

    DataTable dt = new DataTable();
    DataRow dr = null;
    dt.Columns.Add(new DataColumn("S/N", typeof(string)));
    dt.Columns.Add(new DataColumn("Column1", typeof(string)));
    dt.Columns.Add(new DataColumn("Column2", typeof(string)));
    dt.Columns.Add(new DataColumn("Column3", typeof(string)));
    dt.Columns.Add(new DataColumn("Column4", typeof(string)));

    dr = dt.NewRow();
    dr["S/N"] = 1;
    dr["Column1"] = string.Empty;
    dr["Column2"] = string.Empty;
    dr["Column3"] = string.Empty;
    dr["Column4"] = string.Empty;
    dt.Rows.Add(dr);

    //Store the DataTable in ViewState
    ViewState["CurrentTable"] = dt;

    Gridview1.DataSource = dt;
    Gridview1.DataBind();
}
protected void ButtonAdd_Click(object sender, EventArgs e)
{
    AddNewRowToGrid();

    GridViewRow row = (GridViewRow)((sender as Button).NamingContainer);
    Button btn = row.FindControl("ButtonAdd") as Button;
    ScriptManager.GetCurrent(this).RegisterAsyncPostBackControl(btn);  
}

private void AddNewRowToGrid()
{

    int rowIndex = 0;
    if (ViewState["CurrentTable"] != null)
    {
        DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
        DataRow drCurrentRow = null;
        if (dtCurrentTable.Rows.Count > 0)
        {
            //extract the TextBox values
            for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
            {
                //Locate controls in GridView
                DropDownList ddl1 = (DropDownList)Gridview1.Rows[rowIndex].Cells[1].FindControl("EqpCatDDL");
                DropDownList ddl2 = (DropDownList)Gridview1.Rows[rowIndex].Cells[2].FindControl("DescripDDL");
                TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("TextBox3");
                TextBox box4 = (TextBox)Gridview1.Rows[rowIndex].Cells[4].FindControl("TextBox4");

                //Save control values into DataTable
                drCurrentRow = dtCurrentTable.NewRow();
                drCurrentRow["S/N"] = i + 1;
                drCurrentRow["Column1"] = ddl1.SelectedValue.ToString();
                drCurrentRow["Column2"] = ddl2.SelectedValue.ToString();
                drCurrentRow["Column3"] = box3.Text;
                drCurrentRow["Column4"] = box4.Text;

                dtCurrentTable.Rows[rowIndex]["Column1"] = ddl1.SelectedValue.ToString();
                dtCurrentTable.Rows[rowIndex]["Column2"] = ddl2.SelectedValue.ToString();
                dtCurrentTable.Rows[rowIndex]["Column3"] = box3.Text;
                dtCurrentTable.Rows[rowIndex]["Column4"] = box4.Text;

                rowIndex++;
            }

            //add new row to DataTable
            dtCurrentTable.Rows.Add(drCurrentRow);
            //Store the current data to ViewState
            ViewState["CurrentTable"] = dtCurrentTable;

            //Rebind the Grid with the current data
            Gridview1.DataSource = dtCurrentTable;
            Gridview1.DataBind();
        }
    }
    else
    {
        Response.Write("ViewState is null");
    }


    SetPreviousData(); //Set Previous Data from DataTable to GridView on Postbacks from Add New Row button click
}
private void SetPreviousData()
{

    int rowIndex = 0;
    if (ViewState["CurrentTable"] != null)
    {
        DataTable dt = (DataTable)ViewState["CurrentTable"];
        if (dt.Rows.Count > 0)
        {
            for (int i = 0; i < (dt.Rows.Count-1); i++)
            {
                DropDownList ddl1 = (DropDownList)Gridview1.Rows[rowIndex].Cells[1].FindControl("EqpCatDDL");
                DropDownList ddl2 = (DropDownList)Gridview1.Rows[rowIndex].Cells[2].FindControl("DescripDDL");
                TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("TextBox3");
                TextBox box4 = (TextBox)Gridview1.Rows[rowIndex].Cells[4].FindControl("TextBox4");

                ddl1.Text = dt.Rows[i]["Column1"].ToString();
                ddl2.Text = dt.Rows[i]["Column2"].ToString();
                box3.Text = dt.Rows[i]["Column3"].ToString();
                box4.Text = dt.Rows[i]["Column4"].ToString();

                rowIndex++;

            }
        }
    }
}
//Populate Item Name dropdownlist from EqpCat column in EqpCategory table
protected void Gridview1_RowDataBound(object sender, GridViewRowEventArgs e)
{

    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        string connString = ConfigurationManager.ConnectionStrings["MyDbConn"].ConnectionString;
        SqlConnection connection = new SqlConnection(connString);

        //Find the DropDownList in the Row
        DropDownList EqpCatDDL = (e.Row.FindControl("EqpCatDDL") as DropDownList);

        SqlCommand cmd1 = new SqlCommand("SELECT DISTINCT EqpCat FROM EqpCategory", connection);
        cmd1.Connection.Open();

        SqlDataReader ddlValues1;
        ddlValues1 = cmd1.ExecuteReader();

        EqpCatDDL.DataSource = ddlValues1;
        EqpCatDDL.DataTextField = "EqpCat";
        EqpCatDDL.DataValueField = "EqpCat";
        EqpCatDDL.DataBind();

        cmd1.Connection.Close();
        cmd1.Connection.Dispose();

        //Add Default Item in the DropDownList
        EqpCatDDL.Items.Insert(0, new ListItem("--Select--"));
    }

}

//Populate Description dropdownlist based on selected value of Item Name dropdownlist
protected void EqpCatDDL_SelectedIndexChanged(object sender, EventArgs e)
{
    string connString = ConfigurationManager.ConnectionStrings["MyDbConn"].ConnectionString;
    SqlConnection connection = new SqlConnection(connString);

    GridViewRow gvr = (GridViewRow)((DropDownList)sender).Parent.Parent;

    DropDownList EqpCatDDL = gvr.FindControl("EqpCatDDL") as DropDownList;
    DropDownList DescripDDL = gvr.FindControl("DescripDDL") as DropDownList;

    string cate = EqpCatDDL.SelectedValue.ToString();


    SqlCommand cmd2 = new SqlCommand("SELECT Description FROM EqpCategory WHERE EqpCat = '" + cate + "'", connection);
    cmd2.Connection.Open();

    SqlDataReader ddlValues2;
    ddlValues2 = cmd2.ExecuteReader();

    DescripDDL.DataSource = ddlValues2;
    DescripDDL.DataTextField = "Description";
    DescripDDL.DataValueField = "Description";
    DescripDDL.DataBind();

    cmd2.Connection.Close();
    cmd2.Connection.Dispose();

    //Add Default Item in the DropDownList
    DescripDDL.Items.Insert(0, new ListItem("--Select--"));

}

我目前正在使用:带有SSMS 2008的Visual Studio 2010

2 个答案:

答案 0 :(得分:2)

只需修改您的SetPreviousData函数

private void SetPreviousData()
    {

        int rowIndex = 0;
        if (ViewState["CurrentTable"] != null)
        {
            DataTable dt = (DataTable)ViewState["CurrentTable"];
            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < (dt.Rows.Count - 1); i++)
                {
                    DropDownList ddl1 = (DropDownList)Gridview1.Rows[rowIndex].Cells[1].FindControl("EqpCatDDL");
                    DropDownList ddl2 = (DropDownList)Gridview1.Rows[rowIndex].Cells[2].FindControl("DescripDDL");
                    TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("TextBox3");
                    TextBox box4 = (TextBox)Gridview1.Rows[rowIndex].Cells[4].FindControl("TextBox4");

                    ddl1.SelectedValue = dt.Rows[i]["Column1"].ToString();

                    string connString = ConfigurationManager.ConnectionStrings["MyDbConn"].ConnectionString;
                    SqlConnection connection = new SqlConnection(connString);

                    SqlCommand cmd2 = new SqlCommand(""SELECT Description FROM EqpCategory WHERE EqpCat = '" + Convert.ToInt32(ddl1.SelectedValue) + "'", connection);
                    cmd2.Connection.Open();

                    SqlDataReader ddlValues2;
                    ddlValues2 = cmd2.ExecuteReader();
                    ddl2.DataTextField = "Description";
                    ddl2.DataValueField = "Description";
                    ddl2.DataSource = ddlValues2;
                    ddl2.DataBind();

                    cmd2.Connection.Close();
                    cmd2.Connection.Dispose();




                    ddl2.SelectedValue = dt.Rows[i]["Column2"].ToString();
                    box3.Text = dt.Rows[i]["Column3"].ToString();
                    box4.Text = dt.Rows[i]["Column4"].ToString();

                    rowIndex++;

                }
            }
        }
    }

答案 1 :(得分:0)

使用SelectedValuehttps://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listcontrol.selectedvalue(v=vs.110).aspx)代替text来设置所选项目。

例如:

ddl1.SelectedValue = dt.Rows[i]["Column1"].ToString();
ddl2.SelectedValue = dt.Rows[i]["Column2"].ToString();