title: How to properly databind a gridview?
body: <p>So i have a page that contains a gridview, the girdview obtains it's data from an objectdatasource via web service. It contains 2 columns with itemtemplates. for each of these templates when in edit mode, contain dropdownlists which are stored under edititemtemplates. </p>
  
  <p>Everything seems to work fine, except when i am in edit mode and fire the update event, my dropdownlists throw a null reference error. upon further investigation it seems this seems to be caused by the codebehind thinking being unable to locate the dropdroplists. Furthermore when digging through the debugger, it seems that the dropdownlists don't even appear to exist. 
  Although, when on my page the dropdownlists show up when in edit mode, but the codebehind is unable to locate those controls.</p>
  
  <p>What i am guessing is that i am binding the gridview either in the wrong location, or the binding itself is being done incorrectly.</p>
  
  <p>What i would like to know is, why would this situation occur and how can i fix it?
  I would also appreciate if someone could let me know if i am doing my bindings correctly or not. </p>
  
  <p>Below you will find my code for both the gridview and it's codebehind.</p>
  
  <p>GridView:</p>
  
  <pre><code>&lt;asp:GridView ID="GridViewHolder" 
                        runat="server" 
                        AllowPaging="True" 
                        AutoGenerateColumns="False" 
                        BackColor="Transparent" 
                        BorderColor="#999999" 
                        BorderStyle="Ridge" 
                        BorderWidth="3px" 
                        CellPadding="4" 
                        CellSpacing="2" 
                        DataSourceID="MachineDataSet" 
                        ForeColor="Black" 
                        HeaderStyle-HorizontalAlign="Center" 
                        HorizontalAlign="Center"  
                        RowStyle-HorizontalAlign="Center" 
                        Width="796px"
                        OnRowUpdating="GridViewHolder_Updating"
                        OnRowCancelingEdit="GridViewHolder_Canceling"
                        OnRowEditing="GridViewHolder_Editing"
                        OnRowCommand="GridViewHolder_RowCommand"                                                    
                        EnableViewState="False"&gt;
              &lt;RowStyle BackColor="Transparent" 
                        HorizontalAlign="Center" /&gt;
              &lt;Columns&gt;
                  &lt;asp:TemplateField HeaderText="ID" 
                                     SortExpression="ID" 
                                     Visible="False"&gt;
                      &lt;ItemTemplate&gt;
                          &lt;asp:Label ID="MachineIDLabel" 
                                     runat="server" 
                                     Text='&lt;%# Bind("ID") %&gt;'
                                     Visible="false"&gt;&lt;/asp:Label&gt;
                      &lt;/ItemTemplate&gt;
                      &lt;EditItemTemplate&gt;
                          &lt;asp:TextBox ID="MachineIDText" 
                                       runat="server" 
                                       Text='&lt;%# Bind("ID") %&gt;'&gt;
                          &lt;/asp:TextBox&gt;
                      &lt;/EditItemTemplate&gt;
                  &lt;/asp:TemplateField&gt;
                  &lt;asp:BoundField DataField="SiteName" 
                                  HeaderText="Site Name" 
                                  SortExpression="SiteName"
                                  ReadOnly="true" /&gt;
                  &lt;asp:BoundField DataField="Name" 
                                  HeaderText="Machine Name" 
                                  ReadOnly="true" 
                                  SortExpression="Name" /&gt;
                  &lt;asp:TemplateField HeaderText="Machine Type" 
                                     SortExpression="MachineType"&gt;
                      &lt;ItemTemplate&gt;
                          &lt;asp:Label ID="MachineTypeLabel" 
                                     runat="server" 
                                     Text='&lt;%# Bind("MachineType") %&gt;'&gt;
                          &lt;/asp:Label&gt;                            
                      &lt;/ItemTemplate&gt;
                      &lt;EditItemTemplate&gt;
                          &lt;asp:DropDownList ID="MachineTypeDropDown" 
                                            runat="server" 
                                            AppendDataBoundItems="True"                                                
                                            Height="21px" 
                                            Width="217px" 
                                            DataSourceID="GetMachineType" 
                                            DataTextField="Name"                                              
                                            DataValueField="ID"&gt;                                              
                              &lt;asp:ListItem Enabled="true" 
                                            Text="Select a Machine Type." 
                                            Value="empty"&gt;
                              &lt;/asp:ListItem&gt;
                          &lt;/asp:DropDownList&gt;
                      &lt;/EditItemTemplate&gt;
                  &lt;/asp:TemplateField&gt;
                  &lt;asp:TemplateField HeaderText="Machine Model" SortExpression="MachineModel"&gt;
                      &lt;ItemTemplate&gt;
                          &lt;asp:Label ID="MachineModelLabel" 
                                     runat="server" 
                                     Text='&lt;%# Bind("MachineModel") %&gt;'&gt;
                          &lt;/asp:Label&gt;                            
                      &lt;/ItemTemplate&gt;
                      &lt;EditItemTemplate&gt;
                          &lt;asp:DropDownList ID="MachineModelDropDown" 
                                            runat="server" 
                                            AppendDataBoundItems="True"                                                
                                            Height="21px" Width="217px" 
                                            DataSourceID="GetMachineModel" 
                                            DataTextField="Name" 
                                            DataValueField="ID"&gt;                                              
                              &lt;asp:ListItem Enabled="true" 
                                            Text="Select a Machine Model." 
                                            Value="empty"&gt;
                              &lt;/asp:ListItem&gt;
                          &lt;/asp:DropDownList&gt;
                      &lt;/EditItemTemplate&gt;
                  &lt;/asp:TemplateField&gt;
                  &lt;asp:CommandField ButtonType="Button" 
                                    ShowEditButton="True"
                                    CausesValidation="false" &gt;
                      &lt;ItemStyle HorizontalAlign="Center" 
                                 Wrap="True" /&gt;
                  &lt;/asp:CommandField&gt;
              &lt;/Columns&gt;
              &lt;FooterStyle BackColor="Transparent" /&gt;
              &lt;PagerStyle BackColor="Transparent" 
                          ForeColor="Black" 
                          HorizontalAlign="Left" /&gt;
              &lt;SelectedRowStyle BackColor="Transparent" 
                                Font-Bold="True" 
                                ForeColor="White" /&gt;
              &lt;HeaderStyle BackColor="Black" 
                           Font-Bold="True" 
                           ForeColor="White" 
                           HorizontalAlign="Center" /&gt;
       &lt;/asp:GridView&gt;
  </code></pre>
  
  <p>CodeBehind:</p>
  
  <p>Pageload method:</p>
  
  <pre><code>        /// &lt;summary&gt;
      /// Handles the Load event of the Page control.
      /// &lt;/summary&gt;
      /// &lt;param name="sender"&gt;The source of the event.&lt;/param&gt;
      /// &lt;param name="e"&gt;The &lt;see cref="System.EventArgs"/&gt; instance containing the event data.&lt;/param&gt;
      protected void Page_Load(object sender, EventArgs e)
      {
          logger.Debug("Entering Page_Load");
          Boolean loginRequired = true;
          // If no login is required set the session variable and proceed to the main page.
          string str = ConfigurationManager.AppSettings["i0"] as string;
          if (!string.IsNullOrEmpty(str))
          {
              string flag = MyExtensions.Decrypt(str, true);
              if ("false".Equals(flag, StringComparison.InvariantCultureIgnoreCase))
                  loginRequired = true;
              else
              {
                  loginRequired = false;
  
                  // User logged in so check the permissions.
                  UserInfo user = (UserInfo)Session[Constants.LOGGEDINUSER];
                  if (null == user)
                      loginRequired = true;
                  else
                  {
                      string groupId = user.GroupId;
                      if (string.IsNullOrEmpty(groupId))
                          loginRequired = true;
                      else if (!"Admins".Equals(user.GroupId) &amp;&amp; !"Engineer".Equals(user.GroupId))
                          loginRequired = true;
                  }
              }
          }
          if (!Page.IsPostBack)
          {
              Control ctrl = MyExtensions.FindControlRecursive(this, "CommissioningLoginPanel");
              Panel loginPanel = null;
              Panel contentPanel = null;
  
              if (null != ctrl)
              {
                  loginPanel = (Panel)ctrl;
                  ctrl = MyExtensions.FindControlRecursive(this, "CommissioningPanel");
                  if (null != ctrl)
                      contentPanel = (Panel)ctrl;
              }
  
              if (loginRequired)
              {
                  if (null != loginPanel)
                      loginPanel.Visible = true;
                  if (null != contentPanel)
                      contentPanel.Visible = false;
              }
              else
              {
                  if (null != loginPanel)
                      loginPanel.Visible = false;
                  if (null != contentPanel)
                      contentPanel.Visible = true;
              }                
          }
          BindData();
          logger.Debug("Leaving Page_Load");
      }
  </code></pre>
  
  <p>gridview events:</p>
  
  <pre><code>        /// &lt;summary&gt;
      /// Handles the Click event of the update button under edit in the gridview control.
      /// &lt;/summary&gt;
      /// &lt;param name="sender"&gt;The source of the event.&lt;/param&gt;
      /// &lt;param name="e"&gt;The &lt;see cref="System.Web.UI.WebControls.GridViewUpdateEventArgs"/&gt; instance containing the event data.&lt;/param&gt;
      protected void GridViewHolder_Updating(object sender, GridViewUpdateEventArgs e) 
      {
          logger.Debug("Entering GridviewHolder_Updating");
          int machineid;
          string machineid1;
          string machineTypeid;
          string machineModelid;
  
          //retrieve and set the data
          GridViewHolder.EditIndex = e.RowIndex;
  
          try
          {
  
              GridViewRow row = (GridViewRow)GridViewHolder.Rows[e.RowIndex];
              TextBox mID = row.FindControl("MachineIDText") as TextBox;
              DropDownList mType = row.FindControl("MachineTypeDropDown") as DropDownList;
              DropDownList mModel = row.FindControl("MachineModelDropDown") as DropDownList;
  
              machineid1 = mID.Text;
              machineid = Convert.ToInt32(machineid1);
              machineTypeid = mType.SelectedValue;
              machineModelid = mModel.SelectedValue;
  
  
              try
              {
                  if (machineTypeid != "empty" || machineModelid != "empty")
                  {
                      if (machineTypeid != "empty")
                      {
                          inputsService.UpdateMachineTypes(machineid, machineTypeid);
                      }
                      if (machineModelid != "empty")
                      {
                          inputsService.UpdateMachineModels(machineid, machineModelid);
                      }
                      UpdateSucceed.Visible = true;
                      logger.Debug("Updating - Database successfully updated!");
                  }
                  else
                  {
                      UpdateFail.Visible = true;
                      logger.Debug("Updating - Database had no data selected to be updated.");
                  }
              }
              catch (Exception ex)
              {
                  logger.ErrorFormat("Updating - Failed to update the table, ex = {0}", ex);
              }
          }
          catch (Exception ex)
          {
              logger.ErrorFormat("Updating.gathering page controls - Failed to update the table, ex = {0}", ex);
          }
          logger.Debug("Leaving GridViewHolder_Updating");
      }
  
      /// &lt;summary&gt;
      /// Handles the Click event of the cancel button under edit in the gridview control.
      /// &lt;/summary&gt;
      /// &lt;param name="sender"&gt;The source of the event.&lt;/param&gt;
      /// &lt;param name="e"&gt;The &lt;see cref="System.Web.UI.WebControls.GridViewCancelEditEventArgs"/&gt; instance containing the event data.&lt;/param&gt;
      protected void GridViewHolder_Canceling(object sender, GridViewCancelEditEventArgs e)
      {
          logger.Debug("Entering GridViewHolder_Canceling");
          //reset the edit index
          GridViewHolder.EditIndex = -1;
          //Bind data to GridViewHolder
          BindData();
          logger.Debug("Leaving GridViewHolder_Canceling");
      }
  
      /// &lt;summary&gt;
      /// Handles the Click event of the cancel button under edit in the gridview control.
      /// &lt;/summary&gt;
      /// &lt;param name="sender"&gt;The source of the event.&lt;/param&gt;
      /// &lt;param name="e"&gt;The &lt;see cref="System.Web.UI.WebControls.GridViewEditEventArgs"/&gt; instance containing the event data.&lt;/param&gt;
      protected void GridViewHolder_Editing(object sender, GridViewEditEventArgs e)
      {
          logger.Debug("Entering GridViewHolder_Editing");        
          //set the edit index to a new value
          GridViewHolder.EditIndex = e.NewEditIndex;
          //Bind data to gridviewholder
          BindData();
          logger.Debug("Leaving GridViewHolder_Editing");
      }
  </code></pre>
  
  <p>BindData method:</p>
  
  <pre><code> private void BindData()
      {
          logger.Debug("Entering DataBind");
          GridViewHolder.DataSource = Session["MachineTable"];
          GridViewHolder.DataBind();
          logger.Debug("Leaving DataBind");
      }
  </code></pre>
  
  <p>any help or suggestions are greatly appreciated.</p>
  
  <p>Thank you</p>