0

enter image description hereI have a Dropdown1 outside gridview contains three options Select,A,B.

Inside gridview two dropdowns Dropdown2,Dropdown3 in which Dropdown2 contains three options say Select,C,D.

Based on Dropdown1 & Dropdown2, I am populating Dropdown3 using onchange event in javascript in Dropdown2.

everything working fine for First row but when I add new row, Dropdown3 value vanishes to default "Select"

enter image description here

Javascript function

function DataformatFetch(Selection) {
                var status = Selection.options[Selection.selectedIndex].value;
                var row = Selection.parentNode.parentNode;
                var rowIndex = row.rowIndex - 1;

                if (document.getElementById("<%=DropDown1.ClientID%>").value == "A") {
                    var Dataformatlist = row.cells[7].getElementsByTagName('SELECT')[0];                    
                    switch (status) {
                        case "Select":
                            Dataformatlist.options.length = 0;
                            Dataformatlist.options[0] = new Option("Select","Select");
                            break;
                        case "C":
                            Dataformatlist.options.length = 0;
                            Dataformatlist.options[0] = new Option("Select","Select");
                            Dataformatlist.options[1] = new Option("1","1");
                            Dataformatlist.options[2] = new Option("2","2");
                            Dataformatlist.options[3] = new Option("3","3");
                            break;
                        case "D":
                            Dataformatlist.options.length = 0;
                            Dataformatlist.options[0] = new Option("Select","Select");
                            Dataformatlist.options[1] = new Option("11","11");
                            Dataformatlist.options[2] = new Option("22","22");
                            Dataformatlist.options[3] = new Option("33","33");                           
                            break;
                    }
                }

                else if (document.getElementById("<%=DropDown1.ClientID%>").value == "B") {
                    var Dataformatlist = row.cells[7].getElementsByTagName('SELECT')[0];
                    switch (status) {
                        case "Select":
                            Dataformatlist.options.length = 0;
                            Dataformatlist.options[0] = new Option("Select");
                            break;
                        case "C":
                            Dataformatlist.options.length = 0;
                            Dataformatlist.options[0] = new Option("Select","Select");
                            Dataformatlist.options[1] = new Option("111","111");
                            Dataformatlist.options[2] = new Option("222","222");
                            Dataformatlist.options[3] = new Option("333","333");
                            break;
                        case "D":
                            Dataformatlist.options.length = 0;
                            Dataformatlist.options[0] = new Option("Select","Select");
                            Dataformatlist.options[1] = new Option("1111","1111");
                            Dataformatlist.options[2] = new Option("2222","2222");
                            Dataformatlist.options[3] = new Option("3333","3333");
                            break;
                    }
                }                 
            }

ASPX code

<asp:TemplateField HeaderStyle-HorizontalAlign="Left" HeaderText="Object Type">
                                <ItemTemplate>
                                   <asp:DropDownList ID="Dropdownlist2" runat="server" OnChange="DataformatFetch(this);">
                                        <asp:ListItem Value="Select">Select</asp:ListItem>
                                        <asp:ListItem Value="C">C</asp:ListItem>
                                        <asp:ListItem Value="D">D</asp:ListItem>
                                    </asp:DropDownList>
                                </ItemTemplate>
                            </asp:TemplateField>  

C# code

 private void AddNewRowToGrid()
        {
            try
            {
                if (ViewState["CurrentTable"] != null)
                {
                    System.Data.DataTable dtCurrentTable = (System.Data.DataTable)ViewState["CurrentTable"];
                    DataRow drCurrentRow = null;

                    if (dtCurrentTable.Rows.Count > 0)
                    {
                        drCurrentRow = dtCurrentTable.NewRow();
                        //drCurrentRow["REQUESTNO"] = dtCurrentTable.Rows.Count + 1;

                        dtCurrentTable.Rows.Add(drCurrentRow);
                        ViewState["CurrentTable"] = dtCurrentTable;

                        for (int i = 0; i < dtCurrentTable.Rows.Count - 1; i++)
                        {
                            TextBox box2 = (TextBox)DataExchangeGridView.Rows[i].Cells[0].FindControl("PTNTextBox");
                            TextBox box3 = (TextBox)DataExchangeGridView.Rows[i].Cells[1].FindControl("PTDTextBox");
                            TextBox box4 = (TextBox)DataExchangeGridView.Rows[i].Cells[2].FindControl("PTRTextBox");
                            DropDownList box5 = (DropDownList)DataExchangeGridView.Rows[i].Cells[3].FindControl("PIPRDropdownlist");
                            DropDownList box6 = (DropDownList)DataExchangeGridView.Rows[i].Cells[4].FindControl("SupplierNameDroplist");
                            DropDownList box7 = (DropDownList)DataExchangeGridView.Rows[i].Cells[5].FindControl("ObjectTypeDropdownlist");
                            DropDownList box8 = (DropDownList)DataExchangeGridView.Rows[i].Cells[6].FindControl("DataformatDropdownlist");

                            dtCurrentTable.Rows[i]["PARTNUMBER"] = box2.Text;
                            dtCurrentTable.Rows[i]["PARTDESCRIPTION"] = box3.Text;
                            dtCurrentTable.Rows[i]["PARTREVISION"] = box4.Text;
                            dtCurrentTable.Rows[i]["PARTIPR"] = box5.Text;
                            dtCurrentTable.Rows[i]["SUPPLIERNAME"] = box6.Text;
                            dtCurrentTable.Rows[i]["OBJECTTYPE"] = box7.Text;
                            dtCurrentTable.Rows[i]["DATAFORMAT"] = box8.Text;
                        }

                        DataExchangeGridView.DataSource = dtCurrentTable;
                        DataExchangeGridView.DataBind();
                    }
                }
                else
                {
                    Response.Write("ViewState is null");
                }
                SetPreviousData();
            }
            catch (Exception rt)
            {
                rt.ToString();
            }
        }       

        private void SetPreviousData()
        {
            try
            {
                int rowIndex = 0;
                if (this.DataExTypeDropDownList.SelectedItem.Value == "Import")
                {
                    if (ViewState["CurrentTable"] != null)
                    {
                        System.Data.DataTable dt = (System.Data.DataTable)ViewState["CurrentTable"];
                        if (dt.Rows.Count > 0)
                        {
                            for (int i = 0; i < dt.Rows.Count; i++)
                            {
                                System.Web.UI.WebControls.TextBox box2 = (System.Web.UI.WebControls.TextBox)DataExchangeGridView.Rows[rowIndex].Cells[0].FindControl("PTNTextBox");
                                System.Web.UI.WebControls.TextBox box3 = (System.Web.UI.WebControls.TextBox)DataExchangeGridView.Rows[rowIndex].Cells[1].FindControl("PTDTextBox");
                                System.Web.UI.WebControls.TextBox box4 = (System.Web.UI.WebControls.TextBox)DataExchangeGridView.Rows[rowIndex].Cells[2].FindControl("PTRTextBox");
                                box2.Enabled = box3.Enabled = box4.Enabled = false;
                                box2.Text = string.Empty;
                                box3.Text = string.Empty;
                                box4.Text = string.Empty;
                                System.Web.UI.WebControls.DropDownList box5 = (System.Web.UI.WebControls.DropDownList)DataExchangeGridView.Rows[rowIndex].Cells[3].FindControl("PIPRDropdownlist");
                                System.Web.UI.WebControls.DropDownList box6 = (System.Web.UI.WebControls.DropDownList)DataExchangeGridView.Rows[rowIndex].Cells[4].FindControl("SupplierNameDroplist");
                                System.Web.UI.WebControls.DropDownList box7 = (System.Web.UI.WebControls.DropDownList)DataExchangeGridView.Rows[rowIndex].Cells[5].FindControl("ObjectTypeDropdownlist");
                                System.Web.UI.WebControls.DropDownList box8 = (System.Web.UI.WebControls.DropDownList)DataExchangeGridView.Rows[rowIndex].Cells[6].FindControl("DataformatDropdownlist");

                                //FillDropDownList(box8);

                                if (i < dt.Rows.Count - 1)
                                {
                                    box2.Text = dt.Rows[i]["PARTNUMBER"].ToString();
                                    box3.Text = dt.Rows[i]["PARTDESCRIPTION"].ToString();
                                    box4.Text = dt.Rows[i]["PARTREVISION"].ToString();
                                    box5.Text = dt.Rows[i]["PARTIPR"].ToString();
                                    box6.Text = dt.Rows[i]["SUPPLIERNAME"].ToString();
                                    box7.Text = dt.Rows[i]["OBJECTTYPE"].ToString();
                                    //box8.Text = dt.Rows[i]["DATAFORMAT"].ToString();
                                    string XE = box8.Items.FindByText(dt.Rows[i]["DATAFORMAT"].ToString()).Value;
                                    box8.Text = XE;
                                }
                                rowIndex++;
                            }
                        }
                    }
                }
                else if (this.DataExTypeDropDownList.SelectedItem.Value == "Export")
                {
                    if (ViewState["CurrentTable"] != null)
                    {
                        System.Data.DataTable dt = (System.Data.DataTable)ViewState["CurrentTable"];
                        if (dt.Rows.Count > 0)
                        {
                            for (int i = 0; i < dt.Rows.Count; i++)
                            {
                                System.Web.UI.WebControls.TextBox box2 = (System.Web.UI.WebControls.TextBox)DataExchangeGridView.Rows[rowIndex].Cells[0].FindControl("PTNTextBox");
                                System.Web.UI.WebControls.TextBox box3 = (System.Web.UI.WebControls.TextBox)DataExchangeGridView.Rows[rowIndex].Cells[1].FindControl("PTDTextBox");
                                System.Web.UI.WebControls.TextBox box4 = (System.Web.UI.WebControls.TextBox)DataExchangeGridView.Rows[rowIndex].Cells[2].FindControl("PTRTextBox");
                                System.Web.UI.WebControls.DropDownList box5 = (System.Web.UI.WebControls.DropDownList)DataExchangeGridView.Rows[rowIndex].Cells[3].FindControl("PIPRDropdownlist");
                                System.Web.UI.WebControls.DropDownList box6 = (System.Web.UI.WebControls.DropDownList)DataExchangeGridView.Rows[rowIndex].Cells[4].FindControl("SupplierNameDroplist");
                                System.Web.UI.WebControls.DropDownList box7 = (System.Web.UI.WebControls.DropDownList)DataExchangeGridView.Rows[rowIndex].Cells[5].FindControl("ObjectTypeDropdownlist");
                                System.Web.UI.WebControls.DropDownList box8 = (System.Web.UI.WebControls.DropDownList)DataExchangeGridView.Rows[rowIndex].Cells[6].FindControl("DataformatDropdownlist");

                                if (i < dt.Rows.Count - 1)
                                {
                                    box2.Text = dt.Rows[i]["PARTNUMBER"].ToString();
                                    box3.Text = dt.Rows[i]["PARTDESCRIPTION"].ToString();
                                    box4.Text = dt.Rows[i]["PARTREVISION"].ToString();
                                    box5.Text = dt.Rows[i]["PARTIPR"].ToString();
                                    box6.Text = dt.Rows[i]["SUPPLIERNAME"].ToString();
                                    box7.Text = dt.Rows[i]["OBJECTTYPE"].ToString();
                                    box8.Text = dt.Rows[i]["DATAFORMAT"].ToString();
                                }

                                rowIndex++;
                            }
                        }
                    }
                }
            }
            catch (Exception er)
            {
                er.ToString();
            }
        }
kumartyr
  • 305
  • 1
  • 6
  • 19
  • Maybe, post back occurs on add row. If so, then you may need to preserve the value using view state or some other suitable method and set it back to ddl – Chidambaram Dec 08 '17 at 06:27
  • @Chidambaram Can you explain a bit more with sample code please. – kumartyr Dec 08 '17 at 06:57

1 Answers1

0

To start with, the data format is not getting passed back due it being generated client side, so we can add a hidden field to save that value.

<asp:HiddenField ID="selectedValue" runat="server" Value='<%# Eval("Dataformat") %>' />

How we populate that field is adding OnChange to the data format dropdown.

<asp:DropDownList ID="Dropdownlist7" runat="server" OnChange="DataformatSelect(this);">

function DataformatSelect(Selection) {
    var selectedValue = Selection.options[Selection.selectedIndex].value;
    Selection.parentNode.getElementsByTagName('INPUT')[0].value = selectedValue;
}

On the server side, we must return all the data on postback (and on initial load).

private DataTable GetEmptyTable()
{
    var table = new DataTable();
    table.Columns.Add("ObjectType", typeof(string));
    table.Columns.Add("Dataformat", typeof(string));
    return table;
}

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        var table = GetEmptyTable();
        table.Rows.Add("Select", "Select");
        GridView1.DataSource = table;
        GridView1.DataBind();
    }
}

protected void btnAddRow_Click(object sender, EventArgs e)
{
    var table = GetEmptyTable();
    DataRow dr;

    foreach (GridViewRow gvr in GridView1.Rows)
    {
        dr = table.NewRow();
        DropDownList ddlObjectType = gvr.FindControl("Dropdownlist2") as DropDownList;
        HiddenField hdnDataFormat = gvr.FindControl("selectedValue") as HiddenField;

        dr[0] = ddlObjectType.SelectedValue;
        dr[1] = hdnDataFormat.Value;

        table.Rows.Add(dr);
    }

    table.Rows.Add("Select", "Select");

    GridView1.DataSource = table;
    GridView1.DataBind();
}

Ensure the Object Type is getting populated with the Bind.

<asp:DropDownList ID="Dropdownlist2" runat="server" OnChange="DataformatFetch(this);" SelectedValue='<%# Bind("ObjectType") %>'>

Finally, on page load, we need to sync up the client side generated drop down lists.

<body onload="pageLoad();">

function pageLoad() {
    [].forEach.call(document.getElementsByTagName('tr'), function (row, index) {
        if (index == 0) {
            return;
        }

        DataformatFetch(row.cells[0].getElementsByTagName('select')[0]);

        var selectedValue = row.getElementsByTagName('input')[0].value;
        row.cells[1].getElementsByTagName('select')[0].value = selectedValue;
    });
}

Hopefully that fills in any missing gaps to what you already have.

Thanks a lot to add new row in gridview after binding C#, ASP.net

Jaybird
  • 541
  • 4
  • 13
  • I modifed your coding according to my requirement but not getting the desired result. Can you check my C# code and tell me where i going wrong. I have uploaded my whole form for your reference. – kumartyr Dec 11 '17 at 09:39
  • Getting JavaScript runtime error: Unable to get property 'options' of undefined or null reference for this line " var status = Selection.options[Selection.selectedIndex].value;" – kumartyr Dec 11 '17 at 09:57
  • I think I have a different number of columns than you, could you please update this line "DataformatFetch(row.cells[0]..." to "DataformatFetch(row.cells[6]..."? – Jaybird Dec 12 '17 at 00:48
  • I am getting the above error after giving cell value to 6 only. – kumartyr Dec 12 '17 at 03:08
  • and getting JavaScript runtime error: 'pageload' is undefined also – kumartyr Dec 12 '17 at 10:24