title: Adding Dynamic Rows in Gridview and How to retain selected option from user control in Gridview
body: <p>I have created user control named CRE.ascx,this control has 3 dropdownlist.
  First dropdownlist bind data on pageload.Second and third based on SelectedIndexChanged.</p>
  
  <pre><code>    &lt;table cellspacing="0" cellspading="0" style="width:550px;height:30px;"&gt;
          &lt;tr&gt;
              &lt;td style="width:30%;"&gt;
                  &lt;asp:DropDownList ID="ddlCRE" runat="server" Height="20px" Width="145px" OnSelectedIndexChanged="ddlCRE_SelectedIndexChanged" AutoPostBack="true"&gt;
                  &lt;/asp:DropDownList&gt;
              &lt;/td&gt;
              &lt;td style="width:30%;"&gt;
                  &lt;asp:DropDownList ID="ddlDataPoints" runat="server" Height="20px" Width="145px" OnSelectedIndexChanged="ddlDataPoints_SelectedIndexChanged" AutoPostBack="true"&gt;
                  &lt;/asp:DropDownList&gt;
              &lt;/td&gt;
              &lt;td style="width:30%;"&gt;
                  &lt;asp:DropDownList ID="ddlErrorCode" runat="server" Height="20px" Width="145px" OnSelectedIndexChanged="ddlErrorCode_SelectedIndexChanged" AutoPostBack="true"&gt;
                  &lt;/asp:DropDownList&gt;
              &lt;/td&gt;
              &lt;td style="width:10%;"&gt;
                  &lt;asp:TextBox ID="tbxErrorScore" runat="server" style="height:17px;border:0px;font-family:'Segoe UI';font-size:13px;font-weight:500;color:white;background-color:#333333;
                   width:65px;" ReadOnly="true"&gt; &lt;/asp:TextBox&gt;
              &lt;/td&gt;
          &lt;/tr&gt; 
  &lt;/table&gt;
  
  
  
   protected void Page_Load(object sender, EventArgs e)
      {
          if (!IsPostBack)
          {
              //Get Ticket Type Values
              dbtickettype = helpdsktcktusrHandler.GetTicketType("DPT0001");
  
              ddlCRE.DataSource = dbtickettype;
              ddlCRE.DataValueField = "Type_ID";
              ddlCRE.DataTextField = "Type_Name";
              ddlCRE.DataBind();
              ddlCRE.Items.Insert(0, new ListItem("Select Type", "SLCT0000"));
          }
          else
          {
  
          }
      }
  
      protected void ddlCRE_SelectedIndexChanged(object sender, EventArgs e)
      {
          string selectedTypeID = ddlCRE.SelectedValue.ToString();
          try
          {
              if (selectedTypeID == "SLCT0000")
              {
                  ddlDataPoints.Items.Clear();
                  ddlErrorCode.Items.Clear();
                  tbxErrorScore.Text = string.Empty;
              }
              else
              {
                  //Get Category Details
                  dbticketCategory = helpdsktcktusrHandler.GetTicketCategoryDetails(selectedTypeID);
                  //Binding Ticket Type values to Listbox
                  ddlDataPoints.DataSource = dbticketCategory;
                  ddlDataPoints.DataValueField = "Category_ID";
                  ddlDataPoints.DataTextField = "Category_Name";
                  ddlDataPoints.DataBind();
                  ddlDataPoints.Items.Insert(0, new ListItem("Select Category", "SLCT0000"));
                  //Clear Items
                  ddlErrorCode.Items.Clear();
                  tbxErrorScore.Text = string.Empty;
              }
          }
          catch (Exception ex)
          {
  
          }
      }
  
      protected void ddlDataPoints_SelectedIndexChanged(object sender, EventArgs e)
      {
          string selectedCatID = ddlDataPoints.SelectedValue.ToString();
          try
          {
              if (selectedCatID == "SLCT0000")
              {
                  ddlErrorCode.Items.Clear();
                  tbxErrorScore.Text = string.Empty;
              }
              else
              {
                  //Get Category Details
                  dbticketSubCategory = helpdsktcktusrHandler.GetTicketSubCategoryDetails(selectedCatID);
                  //Binding Ticket Type values to Listbox
                  ddlErrorCode.DataSource = dbticketSubCategory;
                  ddlErrorCode.DataValueField = "Sub_Category_ID";
                  ddlErrorCode.DataTextField = "Sub_Category_Name";
                  ddlErrorCode.DataBind();
                  ddlErrorCode.Items.Insert(0, new ListItem("Select Subcategory", "SLCT0000"));
                  //Clear Items
                  tbxErrorScore.Text = string.Empty;
              }
          }
          catch (Exception ex)
          {
          }
      }
  
      protected void ddlErrorCode_SelectedIndexChanged(object sender, EventArgs e)
      {
          string selectedSubcatID = ddlErrorCode.SelectedValue.ToString();
          try
          {
              if (selectedSubcatID == "SLCT0000")
              {
                  tbxErrorScore.Text = string.Empty;
              }
              else
              {
                  //Get Category Details
                  dbticketIssues = helpdsktcktusrHandler.GetTicketIssueDetails(selectedSubcatID);
                  ////Binding Ticket Type values to Listbox
                  //ddlstIssue.DataSource = dbticketIssues;
                  //ddlstIssue.DataValueField = "IssueID";
                  //ddlstIssue.DataTextField = "Issue_Name";
                  //ddlstIssue.DataBind();
  
                  tbxErrorScore.Text = dbticketIssues.Rows[0][1].ToString();
  
              }
          }
          catch (Exception ex)
          {
  
          }
      }
  </code></pre>
  
  <p>then register directive and an instance of the user control added to the page.
  In this main page, i have added one Gridview, user control UC1 and two buttons
  included in the ItemTemplate.</p>
  
  <pre><code>&lt;%@ Register src="~/CRE.ascx" TagName="InsertNewCRE" TagPrefix="uc1"  %&gt;
  &lt;asp:UpdatePanel ID="MainUpdatePanel" runat="server"&gt;
      &lt;ContentTemplate&gt;
          &lt;div id="dvsubCRE" class="dvsubCRE" runat="server"&gt;
              &lt;!-----[[[ GRIDVIEW ADDING CRE  ]]]-----&gt;
              &lt;div id="dvAddingErrorInfo" class="dvAddingErrorInfo"&gt;
                  &lt;!-- LOAD CRE DROPDOWN INFO GRID  --&gt;
                  &lt;asp:GridView ID="gvCREInfo" runat="server" CssClass="gvErrorInfo" AlternatingRowStyle-CssClass="" ShowFooter="false" ShowHeader="false"
                  EnableViewState="True" GridLines="None" EmptyDataText="No records found" AutoGenerateColumns="true" CaptionAlign="Left" CellPadding="0"
                  ShowHeaderWhenEmpty="True" OnRowCreated="gvCREInfo_RowCreated" OnRowCommand="gvCREInfo_RowCommand" &gt;
                      &lt;Columns&gt;
                          &lt;asp:BoundField DataField="RowNumber" /&gt;
                          &lt;asp:TemplateField ItemStyle-Width="25%" ItemStyle-Height="20px"&gt;
                              &lt;ItemTemplate&gt;
                                  &lt;uc1:InsertNewCRE id="UC1InserCRE" runat="server" EnableViewState="true" /&gt;
                              &lt;/ItemTemplate&gt;
                          &lt;/asp:TemplateField&gt;
                          &lt;asp:TemplateField ItemStyle-Width="5%"&gt;
                              &lt;ItemTemplate&gt;
                                  &lt;asp:ImageButton ID="imgbtnAddCRE" runat="server"  Width="20px" Height="20px"  value=""  ImageUrl="~/Images/Tracker/add.png"
                                  CommandName="ButtonAddCRERow" CommandArgument="&lt;%# ((GridViewRow) Container).RowIndex %&gt;"  /&gt;
                                  &lt;asp:ImageButton ID="imgbtnReoveCRE" runat="server" Width="20px" Height="20px"  value="" Visible="false"  ImageUrl="~/Images/Tracker/delete.png" CommandName="ButtonRemoveCRERow" CommandArgument="&lt;%# ((GridViewRow) Container).RowIndex %&gt;" /&gt;
                              &lt;/ItemTemplate&gt;
                          &lt;/asp:TemplateField&gt;
                      &lt;/Columns&gt;
                  &lt;/asp:GridView&gt;
                  &lt;!-- LOAD CRE DROPDOWN INFO GRID CLOSE --&gt;
              &lt;/div&gt;
              &lt;!-----[[[ GRIDVIEW ADDING CRE CLOSE ]]]-----&gt;
          &lt;/div&gt;            
  
      &lt;/ContentTemplate&gt;
  &lt;/asp:UpdatePanel&gt;
  </code></pre>
  
  <p>When main page loads, user control UC1 loaded in the gridview and pull out the data from CRE.ascx page.I have bind dummy data on page load to the gridview.Add new row along with user control mentioned in the RowCommand.</p>
  
  <pre><code>protected void Page_Load(object sender, EventArgs e)
          {
                  try
                  {
                      if (!IsPostBack)
                      {
                          DataTable dt = new DataTable();
                          DataRow dr = null;
                          dt.Columns.Add(new DataColumn("RowNumber", typeof(string)));
                          dr = dt.NewRow();
                          dr["RowNumber"] = 1;
                          dt.Rows.Add(dr);
  
                          ViewState["CurrentTable"] = dt;
  
                          gvCREInfo.DataSource = dt;
                          gvCREInfo.DataBind();
                      }
                      else
                      {
  
  
                      }
                  }
                  catch (Exception ex)
                  {
  
                  }
          }
  
          protected void gvCREInfo_RowCommand(object sender, GridViewCommandEventArgs e)
          {
              #region ADD NEW CRE ROW
              if (e.CommandName == "ButtonAddCRERow")
              {
                  int index = Convert.ToInt32(e.CommandArgument);
                  GridViewRow row = gvCREInfo.Rows[index];
  
                  int count = gvCREInfo.Rows.Count;
                  DataRow drCurrentRow = null;
  
                  UserControl UC1 = (UserControl)(row.Cells[0].FindControl("UC1InserCRE"));
                  DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
  
                  for (int i = 0; i &lt;= (count - 1); i++)
                  {
                      drCurrentRow = dtCurrentTable.NewRow();
                      dtCurrentTable.Rows.Add(drCurrentRow);
                  }
  
                  gvCREInfo.DataSource = dtCurrentTable;
                  gvCREInfo.DataBind();
              }
              #endregion
          }
  </code></pre>
  
  <p>When i run this code working fine and i changed the first dropdownlist
  it will pull data and bind to the second, like wise third one also.But when i click the add button selected data lost in the first row and second row control added not with data.How to retain existing selected data and load user control along with data it should not loss data event post back.Please help me and sort out this.
  ![enter image description here][1]</p>
  
  <p><a href="http://i.stack.imgur.com/wdYZv.jpg" rel="nofollow">http://i.stack.imgur.com/wdYZv.jpg</a></p>