Dropdownlist在gridview中添加动态行时失去选择

时间:2014-04-26 02:59:02

标签: c# asp.net gridview

我在下面有这个代码。我正在尝试按需在gridview中添加行,然后在gridview中绑定下拉列表,并在添加新行时想要保留在上一行中选择的值。问题是我能够绑定下拉列表并进行级联,但是在添加新行时,我无法保留前一行的选择。请查看代码并告诉我错误的地方。

<asp:GridView ID="gvAdvisor" runat="server" ShowFooter="true" AutoGenerateColumns="false" Width="895px" OnRowDataBound="gvAdvisor_RowDataBound">
                                <Columns>
                                    <asp:BoundField DataField="RowNumber" HeaderText="Row Number" />
                                    <asp:TemplateField HeaderText="Region">
                                        <ItemTemplate>
                                            <asp:DropDownList ID="ddRegion" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ddRegion_SelectedIndexChanged">
                                            </asp:DropDownList>
                                        </ItemTemplate>
                                    </asp:TemplateField>
                                    <asp:TemplateField HeaderText="Agency">
                                        <ItemTemplate>
                                            <asp:DropDownList ID="ddAgency" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ddAgency_SelectedIndexChanged">
                                            </asp:DropDownList>
                                        </ItemTemplate>
                                    </asp:TemplateField>
                                    <asp:TemplateField HeaderText="Firm">
                                        <ItemTemplate>
                                            <asp:DropDownList ID="ddFirm" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ddFirm_SelectedIndexChanged">
                                            </asp:DropDownList>
                                        </ItemTemplate>
                                    </asp:TemplateField>
                                    <asp:TemplateField HeaderText="Office">
                                        <ItemTemplate>
                                            <asp:DropDownList ID="ddOffice" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ddOffice_SelectedIndexChanged">
                                            </asp:DropDownList>
                                        </ItemTemplate>
                                    </asp:TemplateField>
                                    <asp:TemplateField HeaderText="Advisor">
                                        <ItemTemplate>
                                            <asp:DropDownList ID="ddAdvisor" runat="server">
                                            </asp:DropDownList>
                                        </ItemTemplate>
                                    </asp:TemplateField>
                                    <asp:TemplateField HeaderText="%">
                                        <ItemTemplate>
                                            <asp:TextBox ID="txtPercent" runat="server" />
                                        </ItemTemplate>
                                        <FooterStyle HorizontalAlign="Right" />
                                        <FooterTemplate>
                                            <asp:Button ID="AddRowButton" runat="server" Text="Add New Row"
                                                OnClick="ButtonAdd_Click" />
                                        </FooterTemplate>
                                    </asp:TemplateField>
                                </Columns>
                            </asp:GridView>





        protected void Page_Load(object sender, EventArgs e)
            {
                if (!IsPostBack)
                {
                    SetInitialRow();
                }
            }


        private void SetInitialRow()
            {
                try
                {
                    DataTable dt = new DataTable();
                    DataRow dr = null;
                    dt.Columns.Add(new DataColumn("RowNumber", 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)));
                    dt.Columns.Add(new DataColumn("Column5", typeof(string)));
                    dt.Columns.Add(new DataColumn("Column6", typeof(string)));


                    dr = dt.NewRow();
                    dr["RowNumber"] = 1;
                    dr["Column1"] = string.Empty;
                    dr["Column2"] = string.Empty;
                    dr["Column3"] = string.Empty;
                    dr["Column4"] = string.Empty;
                    dr["Column5"] = string.Empty;
                    dr["Column6"] = string.Empty;

                    dt.Rows.Add(dr);

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

                    gvAdvisor.DataSource = dt;
                    gvAdvisor.DataBind();
                }
                catch (Exception Ex)
                { 
                    //logger.Info("SetInitialRow : " + Ex.Message); 
                }
            }

    private void AddNewRowToGrid()
        {
            try
            {
                int rowIndex = 0;
                if (ViewState["CurrentTable"] != null)
                {
                    DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
                    DataRow drCurrentRow = null;
                    if (dtCurrentTable.Rows.Count > 0)
                    {
                        //extract the TextBox values

                        //if (tbBushels.Text != "" && tbLocation.Text != "" && tbFuture.Text != "" && tbBasis.Text != "" && tbPrice.Text != "" && tbRevenue.Text != "")
                        //{
                        for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
                        {
                            DropDownList Region =
                                (DropDownList)gvAdvisor.Rows[rowIndex].Cells[1].FindControl("ddRegion");
                            DropDownList Agency =
                                (DropDownList)gvAdvisor.Rows[rowIndex].Cells[2].FindControl("ddAgency");
                            DropDownList Firm =
                                (DropDownList)gvAdvisor.Rows[rowIndex].Cells[3].FindControl("ddFirm");
                            DropDownList Office =
                                (DropDownList)gvAdvisor.Rows[rowIndex].Cells[4].FindControl("ddOffice");
                            DropDownList Advisor =
                                (DropDownList)gvAdvisor.Rows[rowIndex].Cells[5].FindControl("ddAdvisor");
                            TextBox Percent =
                                (TextBox)gvAdvisor.Rows[rowIndex].Cells[6].FindControl("txtPercent");


                            drCurrentRow = dtCurrentTable.NewRow();
                            drCurrentRow["RowNumber"] = i + 1;                        
                            drCurrentRow["Column1"] = Region.SelectedItem.Value;
                            drCurrentRow["Column2"] = Agency.SelectedItem.Value;
                            drCurrentRow["Column3"] = Firm.SelectedItem.Value;
                            drCurrentRow["Column4"] = Office.SelectedItem.Value;
                            drCurrentRow["Column5"] = Advisor.SelectedItem.Value;
                            drCurrentRow["Column6"] = Percent.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
                        gvAdvisor.DataSource = dtCurrentTable;
                        gvAdvisor.DataBind();

                        //}
                    }

                }
                else
                {
                    Response.Write("ViewState is null");
                }

                //Set Previous Data on Postbacks
                SetPreviousData();
            }
            catch (Exception Ex)
            { 
                //logger.Info("AddNewRowToGrid : " + Ex.Message);
            }
        }

        private void SetPreviousData()
        {
            try
            {
                int rowIndex = 0;
                if (ViewState["CurrentTable"] != null)
                {
                    DataTable dt = (DataTable)ViewState["CurrentTable"];
                    if (dt.Rows.Count > 0)
                    {
                        for (int i = 1; i < dt.Rows.Count; i++)
                        {                        
                            DropDownList Region =
                                (DropDownList)gvAdvisor.Rows[rowIndex].Cells[1].FindControl("ddRegion");
                            Region.SelectedItem.Value = dt.Rows[i]["Column1"].ToString();
                            foreach (GridViewRow gvr in gvAdvisor.Rows)
                            {
                                if (gvr.RowType == DataControlRowType.DataRow)
                                {
                                   // DropDownList ddRegion = (DropDownList)gvr.FindControl("ddRegion");
                                    DropDownList ddAgency = (DropDownList)gvr.FindControl("ddAgency");

                                    if (Region.SelectedItem.Value == "0")
                                    {

                                    }
                                    else
                                    {
                                        ddHelp.BindAgencyByRegion(ddAgency, Convert.ToInt32(Region.SelectedItem.Value));
                                    }
                                    ListItem ll1 = new ListItem("Select", "0");
                                    ddAgency.Items.Insert(0, ll1);
                                }
                            }

                            DropDownList Agency =
                                (DropDownList)gvAdvisor.Rows[rowIndex].Cells[2].FindControl("ddAgency");
                            Agency.SelectedItem.Value = dt.Rows[i]["Column2"].ToString();
                            foreach (GridViewRow gvr in gvAdvisor.Rows)
                            {
                                if (gvr.RowType == DataControlRowType.DataRow)
                                {
                                    //DropDownList ddAgency = (DropDownList)gvr.FindControl("ddAgency");
                                    DropDownList ddFirm = (DropDownList)gvr.FindControl("ddFirm");

                                    if (Agency.SelectedItem.Value == "0")
                                    {

                                    }
                                    else
                                    {
                                        ddHelp.BindFirm(ddFirm, Convert.ToInt32(Agency.SelectedItem.Value));
                                    }
                                    ListItem ll2 = new ListItem("Select", "0");
                                    ddFirm.Items.Insert(0, ll2);
                                }
                            }

                            DropDownList Firm =
                                (DropDownList)gvAdvisor.Rows[rowIndex].Cells[3].FindControl("ddFirm");
                            Firm.SelectedItem.Value = dt.Rows[i]["Column3"].ToString();
                            foreach (GridViewRow gvr in gvAdvisor.Rows)
                            {
                                if (gvr.RowType == DataControlRowType.DataRow)
                                {
                                    //DropDownList ddFirm = (DropDownList)gvr.FindControl("ddFirm");
                                    DropDownList ddOffice = (DropDownList)gvr.FindControl("ddOffice");

                                    if (Firm.SelectedItem.Value == "0")
                                    {

                                    }
                                    else
                                    {
                                        ddHelp.BindOffice(ddOffice, 0, Convert.ToInt32(Firm.SelectedItem.Value), 0);
                                    }
                                    ListItem ll3 = new ListItem("Select", "0");
                                    ddOffice.Items.Insert(0, ll3);
                                }
                            }
                            DropDownList Office =
                                (DropDownList)gvAdvisor.Rows[rowIndex].Cells[4].FindControl("ddOffice");
                            Office.SelectedItem.Value = dt.Rows[i]["Column4"].ToString();
                            foreach (GridViewRow gvr in gvAdvisor.Rows)
                            {
                                if (gvr.RowType == DataControlRowType.DataRow)
                                {
                                    //DropDownList ddOffice = (DropDownList)gvr.FindControl("ddOffice");
                                    DropDownList ddAdvisor = (DropDownList)gvr.FindControl("ddAdvisor");

                                    if (Office.SelectedItem.Value == "0")
                                    {

                                    }
                                    else
                                    {
                                        ddHelp.BindAdvisor(ddAdvisor, 0, 0, Convert.ToInt32(Office.SelectedItem.Value));
                                    }
                                    ListItem ll4 = new ListItem("Select", "0");
                                    ddAdvisor.Items.Insert(0, ll4);
                                }
                            }
                            DropDownList Advisor = 
                                (DropDownList)gvAdvisor.Rows[rowIndex].Cells[5].FindControl("ddAdvisor");
                            TextBox Percent =
                                (TextBox)gvAdvisor.Rows[rowIndex].Cells[6].FindControl("txtPercent");


                            Advisor.SelectedItem.Value = dt.Rows[i]["Column5"].ToString();
                            Percent.Text = dt.Rows[i]["Column6"].ToString();

                            rowIndex++;
                        }
                    }
                }
            }
            catch (Exception Ex)
            { 
                //logger.Info("SetPreviousData : " + Ex.Message); 
            }
        }

protected void ButtonAdd_Click(object sender, EventArgs e)
    {
        AddNewRowToGrid();

    }

2 个答案:

答案 0 :(得分:0)

gvAdvisor_RowDataBound event

  1. 将viewstate [currenttable]中的数据分配给数据表
  2. foreach datarow有一个使用行索引的循环
  3. 使用行索引和列名
  4. 将数据表中的值分配给下拉列表

    示例:(Dropdownlist)(gvAdvisor.Rows[i].findcontrol("ddRegion")).SelectedValue = datatable[i]["Region"];

    您需要调整上述代码以最适合您的网格视图

    您也可以对其他控件使用类似的逻辑Checkboxradiobuttons

答案 1 :(得分:0)

protected void gvAdvisor_RowDataBound(object sender, GridViewRowEventArgs e) 
{
if (ViewState["CurrentTable"] != null) 
{
Datatable dt = (Datatable)ViewState["CurrentTable"];
if (e.Row.RowType == DataControlRowType.DataRow) 
{ 

((DropDownList)gvAdvisor.Rows[rowIndex].FindControl("ddRegion")).SelectedValue =    dt[rowindex]["Column1"];
((DropDownList)gvAdvisor.Rows[rowIndex].FindControl("ddRegion")).Items.Insert(0,new  ListItem("Select", "0"));

}
}
else
{
SetInitialRow(); 
} 
}