ASP.Net中GridView内的DropDownList数据绑定

时间:2014-07-21 07:44:13

标签: c# asp.net gridview

我有一个gridview MyGridView,它包含两个DropDownLists和一个TextBox。过程是,我从第一个DropDownList中选择一个项目,在第二个DropDown中填充与所选项目相关的项目。我在文本框中输入一些文本,然后按下"添加"在gridview的页脚中,创建一个新行。但第一行仍有数据。

我使用Dictionary填充DropDowns。在第一个下拉列表的SelectedIndexChanged事件中,为第二个下拉列表创建一个新字典。

当我点击添加按钮时,文本框数据会保留,但下拉列表中会出现这种情况。数据源丢失。

如何在以前的行中保留数据?

**编辑:请参阅代码。我在http://www.codeproject.com/Articles/467788/Dynamically-adding-and-deleting-rows-from-ASP-NET **

使用了教程

代码:

GridView代码

    <asp:GridView ID="SODetailsGrid" runat="server" ShowFooter="True" 
                AutoGenerateColumns="False" OnRowDeleting="SODetailsGrid_RowDeleting"
                Width="97%" Style="text-align: left" ondatabound="SODetailsGrid_DataBound" 
                onrowdatabound="SODetailsGrid_RowDataBound">
                <Columns>
                   <asp:BoundField DataField="RowNumber" HeaderStyle-CssClass="first-name" 
                        HeaderText="SNo" Visible="false">
                    <HeaderStyle CssClass="first-name" />
                    </asp:BoundField>
<asp:TemplateField HeaderText="Category">
                    <ItemTemplate>
                        <asp:DropDownList ID="ddlCategory" AutoPostBack="true" CssClass="txt"  runat="server" AppendDataBoundItems="true" onselectedindexchanged="ddlCategory_SelectedIndexChanged">
                        </asp:DropDownList>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="ddlCategory"
                                ErrorMessage="*" SetFocusOnError="True"></asp:RequiredFieldValidator>
                    </ItemTemplate>
                    <FooterStyle HorizontalAlign="Center" />
                    <FooterTemplate>
                        <asp:Button ID="ButtonAdd" runat="server" CssClass="r_button" Text="Add New Item" onclick="ButtonAdd_Click" Width="120px" />
                    </FooterTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Item">
                    <ItemTemplate>
                        <asp:DropDownList ID="ddlItem"  AutoPostBack="true" CssClass="txt" runat="server" AppendDataBoundItems="true" onselectedindexchanged="ddlItem_SelectedIndexChanged">
                        </asp:DropDownList>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="ddlItem"
                                ErrorMessage="*" SetFocusOnError="True"></asp:RequiredFieldValidator>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Qty" HeaderStyle-CssClass="first-name">
                    <ItemTemplate>
                        <asp:TextBox ID="textQty" CssClass="txt"   runat="server" AppendDataBoundItems="true">
                        </asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="textQty"
                                ErrorMessage="*" SetFocusOnError="True"></asp:RequiredFieldValidator>
                    </ItemTemplate>
                    <HeaderStyle CssClass="first-name" />
                </asp:TemplateField>                
                <asp:TemplateField HeaderText="Disc%" >
                    <ItemTemplate>
                        <asp:TextBox ID="textDiscount" CssClass="txt" runat="server" AppendDataBoundItems="true" >
                        </asp:TextBox>
                            <asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ControlToValidate="textDiscount"
                                ErrorMessage="*"></asp:RequiredFieldValidator>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Amount" HeaderStyle-CssClass="first-name">
                    <ItemTemplate>
                        <asp:TextBox ID="textAmount" CssClass="txt" runat="server" AppendDataBoundItems="true">
                        </asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator5" runat="server" ControlToValidate="textAmount"
                                ErrorMessage="*" ></asp:RequiredFieldValidator>
                    </ItemTemplate>
                    <HeaderStyle CssClass="first-name" />
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Planned Delivery Date">
                    <ItemTemplate>
                        <asp:TextBox ID="textPDelivery" CssClass="txt" runat="server" AppendDataBoundItems="true">
                        </asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator7" runat="server" ControlToValidate="textPDelivery"
                                ErrorMessage="*" ></asp:RequiredFieldValidator>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Planned Shipment Date" >
                    <ItemTemplate>
                        <asp:TextBox ID="textPShipment" CssClass="txt" runat="server" AppendDataBoundItems="true">
                        </asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator8" runat="server" ControlToValidate="textPShipment"
                                ErrorMessage="*" ></asp:RequiredFieldValidator>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:CommandField ShowDeleteButton="True" />
                </Columns>
            </asp:GridView>

背后的代码:

    public partial class newso : System.Web.UI.Page
    {
        DataTable dt;
        public string itemurl = myur;
        public string itemcaturl = mysecondurl;
        public string uniturl = mythirdurl;
        public string token;
        public Dictionary<string, int> itemMap = new Dictionary<string, int>();
        public Dictionary<int, string> itemDictionary;
        public Dictionary<int, string> itemcatDictionary;
        public DropDownList ddlItem;
        public DropDownList ddlCategory;
        protected void Page_Load(object sender, EventArgs e)
        {
            token = Session["token"].ToString();
            if (!IsPostBack)
            {
                   try
                    {
                        string itemcategory = GetJSON(itemcaturl);
                        bindItemCatNameDDL(itemcategory);
                        string units = GetJSON(uniturl);
                        bindUnitDDL(units);
                    }
                    catch (Exception ex)
                    {
                    }
                }
                FirstGridViewRow();                  
        }                    

        public string GetJSON(string myurl)
        {
            string formattedUri = String.Format(CultureInfo.InvariantCulture, myurl);    
            HttpWebRequest webRequest = GetWebRequest(formattedUri);
            webRequest.ContentType = "application/json; charset=utf-8";
            webRequest.Headers.Add("X-Token", token);
            HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
            string jsonResponse = string.Empty;
            using (StreamReader sr = new StreamReader(response.GetResponseStream()))
            {
                jsonResponse = sr.ReadToEnd();
            }
            return jsonResponse;
        }

        private HttpWebRequest GetWebRequest(string formattedUri)
        {
            // Create the request’s URI.
            Uri serviceUri = new Uri(formattedUri, UriKind.Absolute);
            // Return the HttpWebRequest.
            return (HttpWebRequest)System.Net.WebRequest.Create(serviceUri);
        }              
        public void bindItemNameDDL(string items, int cat, object sender)
        {
            itemDictionary = new Dictionary<int, string>();
            string newitemjson = "{\"data\":" + items + "}";
            itemDictionary.Add(0, "Select");

            IList<Item> item = new JavaScriptSerializer().Deserialize<IList<Item>>(items);

            GridViewRow gvr = (GridViewRow)(((Control)sender).NamingContainer);
            ddlItem = (DropDownList)gvr.FindControl("ddlItem");
            ddlItem.DataSource = item; 
            ddlItem.DataTextField = "Item_Name";
            ddlItem.DataValueField = "RowNum";
            ddlItem.DataBind();                
        }
        public void bindItemCatNameDDL(string itemcats)
        {
            itemcatDictionary = new Dictionary<int, string>();
            string newitemcatjson = "{\"data\":" + itemcats + "}";
            itemcatDictionary.Add(0, "Select");
            ItemCategory itemcatDetails = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<ItemCategory>(newitemcatjson);
            foreach (var item in itemcatDetails.data)
            {
                Console.WriteLine("id: {0}, name: {1}", item.RowNum, item.ItemCategory_Name);
                itemcatDictionary.Add(item.RowNum, item.ItemCategory_Name);
            }
            ddlItem.DataSource = itemcatDictionary; 

        }       
        public void bindUnitDDL(string units)
        {
            Dictionary<int, string> unitDictionary = new Dictionary<int, string>();
            string newunitjson = "{\"data\":" + units + "}";

            Units unitDetails = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<Units>(newunitjson);
            foreach (var item in unitDetails.data)
            {
                Console.WriteLine("id: {0}, name: {1}", item.RowNum, item.Unit_Name);
                unitDictionary.Add(item.RowNum, item.Unit_Name);
            }
        }          
        /*
         * Fill data to dropdownlists
         */
        protected void SODetailsGrid_DataBound(object sender, EventArgs e)
        {

        }        
        protected void SODetailsGrid_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                //Find the DropDownList in the Row
                ddlCategory = (e.Row.FindControl("ddlCategory") as DropDownList);
                ddlCategory.DataSource = itemcatDictionary;
                ddlCategory.DataTextField = "Value";
                ddlCategory.DataValueField = "Key";
                ddlCategory.DataBind();
                ddlItem = (e.Row.FindControl("ddlItem") as DropDownList);
            }
        }

        protected void ddlCategory_SelectedIndexChanged(object sender, EventArgs e)
        {
            string items = GetJSON(itemurl);
            GridViewRow gvr = (GridViewRow)(((Control)sender).NamingContainer);
            ddlCategory = (DropDownList)gvr.FindControl("ddlCategory");
            ddlItem = (DropDownList)gvr.FindControl("ddlItem");
            bindItemNameDDL(items, Convert.ToInt32(ddlCategory.SelectedItem.Value),sender);
        }

        protected void ddlItem_SelectedIndexChanged(object sender, EventArgs e)
        {
            GridViewRow gvr = (GridViewRow)(((Control)sender).NamingContainer);
            ddlItem = (DropDownList)gvr.FindControl("ddlItem");

        }               
        protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
        {


        }  

        private void FirstGridViewRow()
        {
            DataTable dt = new DataTable();
            DataRow dr = null;
            dt.Columns.Add(new DataColumn("RowNumber", typeof(string)));
            dt.Columns.Add(new DataColumn("Col1", typeof(string)));
            dt.Columns.Add(new DataColumn("Col2", typeof(string)));
            dt.Columns.Add(new DataColumn("Col3", typeof(string)));
            dt.Columns.Add(new DataColumn("Col4", typeof(string)));
            dt.Columns.Add(new DataColumn("Col5", typeof(string)));
            dt.Columns.Add(new DataColumn("Col6", typeof(string)));
            dt.Columns.Add(new DataColumn("Col7", typeof(string)));
            dr = dt.NewRow();
            dr["RowNumber"] = 1;
            dr["Col1"] = string.Empty;
            dr["Col2"] = string.Empty;
            dr["Col3"] = string.Empty;
            dr["Col4"] = string.Empty;
            dr["Col5"] = string.Empty;
            dr["Col6"] = string.Empty;
            dr["Col7"] = string.Empty;
            dt.Rows.Add(dr);    
            ViewState["CurrentTable"] = dt;      
            SODetailsGrid.DataSource = dt;
            SODetailsGrid.DataBind();    
            Button btnAdd = (Button)SODetailsGrid.FooterRow.Cells[6].FindControl("ButtonAdd");
            //Page.Form.DefaultFocus = btnAdd.ClientID;       
        }
        private void AddNewRow()
        {
            int rowIndex = 0;    
            if (ViewState["CurrentTable"] != null)
            {
                DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
                DataRow drCurrentRow = null;
                if (dtCurrentTable.Rows.Count > 0)
                {
                    for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
                    {
                        DropDownList ddlCategory = (DropDownList)SODetailsGrid.Rows[rowIndex].Cells[1].FindControl("ddlCategory");
                        DropDownList ddlItem = (DropDownList)SODetailsGrid.Rows[rowIndex].Cells[2].FindControl("ddlItem");
                        TextBox textQty = (TextBox)SODetailsGrid.Rows[rowIndex].Cells[3].FindControl("textQty");
                        TextBox textDiscount = (TextBox)SODetailsGrid.Rows[rowIndex].Cells[4].FindControl("textDiscount");
                        TextBox textAmount = (TextBox)SODetailsGrid.Rows[rowIndex].Cells[5].FindControl("textAmount");
                        TextBox textPDelivery = (TextBox)SODetailsGrid.Rows[rowIndex].Cells[6].FindControl("textPDelivery");
                        TextBox textPShipment = (TextBox)SODetailsGrid.Rows[rowIndex].Cells[7].FindControl("textPShipment");       
                        drCurrentRow = dtCurrentTable.NewRow();
                        drCurrentRow["RowNumber"] = i + 1;    
                        dtCurrentTable.Rows[i - 1]["Col1"] = ddlCategory.SelectedValue;
                        dtCurrentTable.Rows[i - 1]["Col2"] = ddlItem.SelectedValue;
                        dtCurrentTable.Rows[i - 1]["Col3"] = textQty.Text;
                        dtCurrentTable.Rows[i - 1]["Col4"] = textDiscount.Text;
                        dtCurrentTable.Rows[i - 1]["Col5"] = textAmount.Text;
                        dtCurrentTable.Rows[i - 1]["Col6"] = textPDelivery.Text;
                        dtCurrentTable.Rows[i - 1]["Col7"] = textPShipment.Text;
                        rowIndex++;
                    }
                    dtCurrentTable.Rows.Add(drCurrentRow);
                    ViewState["CurrentTable"] = dtCurrentTable;
                    DebugTable(dtCurrentTable);
                    SODetailsGrid.DataSource = dtCurrentTable;
                    SODetailsGrid.DataBind();

                    DropDownList ddlcat = (DropDownList)SODetailsGrid.Rows[1].Cells[1].FindControl("ddlCategory");
                    ddlcat.Focus();
                    // txn.Focus;
                }
            }
            else
            {
                Response.Write("ViewState is null");
            }
            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; i++)
                    {       
                        DropDownList ddlCategory = (DropDownList)SODetailsGrid.Rows[rowIndex].Cells[1].FindControl("ddlCategory");
                        DropDownList ddlItem = (DropDownList)SODetailsGrid.Rows[rowIndex].Cells[2].FindControl("ddlItem");
                        TextBox textQty = (TextBox)SODetailsGrid.Rows[rowIndex].Cells[3].FindControl("textQty");
                        TextBox textDiscount = (TextBox)SODetailsGrid.Rows[rowIndex].Cells[4].FindControl("textDiscount");
                        TextBox textAmount = (TextBox)SODetailsGrid.Rows[rowIndex].Cells[5].FindControl("textAmount");
                        TextBox textPDelivery = (TextBox)SODetailsGrid.Rows[rowIndex].Cells[6].FindControl("textPDelivery");
                        TextBox textPShipment = (TextBox)SODetailsGrid.Rows[rowIndex].Cells[7].FindControl("textPShipment");       
                        ddlCategory.SelectedValue = dt.Rows[i]["Col1"].ToString();
                        ddlItem.SelectedValue = dt.Rows[i]["Col2"].ToString();
                        textQty.Text = dt.Rows[i]["Col3"].ToString();
                        textDiscount.Text = dt.Rows[i]["Col4"].ToString();
                        textAmount.Text = dt.Rows[i]["Col5"].ToString();
                        textPDelivery.Text = dt.Rows[i]["Col6"].ToString();
                        textPShipment.Text = dt.Rows[i]["Col7"].ToString();       
                        rowIndex++;
                    }
                }
            }
        }
        protected void ButtonAdd_Click(object sender, EventArgs e)
        {
            AddNewRow();
        }
        protected void SODetailsGrid_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            SetRowData();
            if (ViewState["CurrentTable"] != null)
            {
                DataTable dt = (DataTable)ViewState["CurrentTable"];
                DataRow drCurrentRow = null;
                int rowIndex = Convert.ToInt32(e.RowIndex);
                if (dt.Rows.Count > 1)
                {
                    dt.Rows.Remove(dt.Rows[rowIndex]);
                    drCurrentRow = dt.NewRow();
                    ViewState["CurrentTable"] = dt;
                    SODetailsGrid.DataSource = dt;
                    SODetailsGrid.DataBind();

                    for (int i = 0; i < SODetailsGrid.Rows.Count - 1; i++)
                    {
                        SODetailsGrid.Rows[i].Cells[0].Text = Convert.ToString(i + 1);
                    }
                    SetPreviousData();
                }
            }
        }

        private void SetRowData()
        {
            int rowIndex = 0;

            if (ViewState["CurrentTable"] != null)
            {
                DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
                DataRow drCurrentRow = null;
                if (dtCurrentTable.Rows.Count > 0)
                {
                    for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
                    {       
                        DropDownList ddlCategory = (DropDownList)SODetailsGrid.Rows[rowIndex].Cells[1].FindControl("ddlCategory");
                        DropDownList ddlItem = (DropDownList)SODetailsGrid.Rows[rowIndex].Cells[2].FindControl("ddlItem");
                        TextBox textQty = (TextBox)SODetailsGrid.Rows[rowIndex].Cells[3].FindControl("textQty");
                        TextBox textDiscount = (TextBox)SODetailsGrid.Rows[rowIndex].Cells[4].FindControl("textDiscount");
                        TextBox textAmount = (TextBox)SODetailsGrid.Rows[rowIndex].Cells[5].FindControl("textAmount");
                        TextBox textPDelivery = (TextBox)SODetailsGrid.Rows[rowIndex].Cells[6].FindControl("textPDelivery");
                        TextBox textPShipment = (TextBox)SODetailsGrid.Rows[rowIndex].Cells[7].FindControl("textPShipment");
                        drCurrentRow = dtCurrentTable.NewRow();
                        drCurrentRow["RowNumber"] = i + 1;
                        dtCurrentTable.Rows[i - 1]["Col1"] = ddlCategory.SelectedValue;
                        dtCurrentTable.Rows[i - 1]["Col2"] = ddlItem.SelectedValue;
                        dtCurrentTable.Rows[i - 1]["Col3"] = textQty.Text;
                        dtCurrentTable.Rows[i - 1]["Col4"] = textDiscount.Text;
                        dtCurrentTable.Rows[i - 1]["Col5"] = textAmount.Text;
                        dtCurrentTable.Rows[i - 1]["Col6"] = textPDelivery.Text;
                        dtCurrentTable.Rows[i - 1]["Col7"] = textPShipment.Text;
                        rowIndex++;
                    }

                    ViewState["CurrentTable"] = dtCurrentTable;
                }
            }
            else
            {
                Response.Write("ViewState is null");
            }
            //SetPreviousData();
        }
        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                SetRowData();
                DataTable table = ViewState["CurrentTable"] as DataTable;

            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
}
}

0 个答案:

没有答案