This is a migrated thread and some comments may be shown as answers.

Rebind Server Side - Not working after row added

4 Answers 160 Views
Grid
This is a migrated thread and some comments may be shown as answers.
PAYDAY
Top achievements
Rank 1
PAYDAY asked on 21 Jan 2009, 12:39 PM

I have an issue when trying to get the data grid to rebind after an item has been inserted. One thing to note is that I put all items in edit mode upon load. This is working fine. When I click the Add New command on the grid, I fire the ItemCommand event, add a row to the database, then set the grid Datasource to null and rebind.

The flow should be like this:
Initial Load (works properly):
-RadGrid1_NeedDataSource
 - PopulateGrid()
RadGrid1_ItemCreated
 - Populate()
 - PopulateEntity()
RadGrid1_ItemDataBound
 - PopulateDetCodeList()
RadGrid1_PreRender

Click Add New Command:
RadGrid1_ItemCreated
RadGrid1_ItemCommand
 - AddNewItem()
 - PopulateGrid() (note: allowRebind = true)

//this happens when Rebind() is called in PopulateGrid()
RadGrid1_ItemDataBound 
RadGrid1_ItemCreated
 - Populate()
 - PopulateEntity()
RadGrid1_PreRender

NOTICE That RadGrid1_NeedDataSource() event is not called when Add New Command is fired.

Here is my code:

<telerik:RadGrid ID="RadGrid1" runat="server" EnableEmbeddedSkins="false"
 Skin="PayDayUsa" AutoGenerateColumns="false" AutoGenerateEditColumn="False" GridLines="None"
 OnNeedDataSource="RadGrid1_NeedDataSource" OnItemCreated="RadGrid1_ItemCreated"
 OnItemDataBound="RadGrid1_ItemDataBound" OnItemCommand="RadGrid1_ItemCommand"
 AllowPaging="True" AllowSorting="True" AllowMultiRowEdit="true" OnPreRender="RadGrid1_PreRender">
 <PagerStyle Mode="NextPrevAndNumeric" />
 <MasterTableView CommandItemDisplay="Top" EditMode="InPlace" ExpandCollapseColumn-Display="false">
   <Columns>
     <telerik:GridTemplateColumn UniqueName="TemplateColumn" HeaderText="Code">
       <ItemTemplate>
         <asp:Label ID="DetCode" runat="server" Text='<%#Eval("DetCode") %>'></asp:Label>
       </ItemTemplate>
       <EditItemTemplate>
         <telerik:RadComboBox ID="DetCode" runat="server">
         </telerik:RadComboBox>
       </EditItemTemplate>
     </telerik:GridTemplateColumn>
     <telerik:GridTemplateColumn UniqueName="TemplateColumn" HeaderText="Hours">
       <ItemTemplate>
         <asp:Label ID="Hours" runat="server" Text='<%#Eval("Hours") %>'></asp:Label>
       </ItemTemplate>
       <EditItemTemplate>
         <telerik:RadNumericTextBox ID="Hours" runat="server">
         </telerik:RadNumericTextBox>
       </EditItemTemplate>
     </telerik:GridTemplateColumn>
     <telerik:GridTemplateColumn UniqueName="TemplateColumn" HeaderText="Rate">
       <ItemTemplate>
         <asp:Label ID="Rate" runat="server" Text='<%#Eval("Rate") %>'></asp:Label>
       </ItemTemplate>
       <EditItemTemplate>
         <telerik:RadNumericTextBox ID="Rate" runat="server">
         </telerik:RadNumericTextBox>
       </EditItemTemplate>
     </telerik:GridTemplateColumn>
     <telerik:GridTemplateColumn UniqueName="TemplateColumn" HeaderText="Amount">
       <ItemTemplate>
         <asp:Label ID="Amount" runat="server" Text='<%#Eval("Amount") %>'></asp:Label>
       </ItemTemplate>
       <EditItemTemplate>
         <telerik:RadNumericTextBox ID="Amount" runat="server">
         </telerik:RadNumericTextBox>
       </EditItemTemplate>
     </telerik:GridTemplateColumn>
   </Columns>
 </MasterTableView>
 <FilterMenu EnableTheming="True">
   <CollapseAnimation Type="OutQuint" Duration="200"></CollapseAnimation>
 </FilterMenu>
</telerik:RadGrid>

private void PopulateDetCodeList(GridEditableItem item)
{
  //dropdown list in grid
  RadComboBox list = (RadComboBox)item["TemplateColumn"].FindControl("DetCode");
  list.DataTextField = CDetCodesList.DBFieldName.DataText.ToString();
  list.DataValueField = CDetCodesList.DBFieldName.DataValue.ToString();
  list.DataSource = CDetCodesList.GetList();
  list.DataBind();
}

 

private void PopulateGrid(bool allowRebind)
{
  this.MyDatabaseData = null;
  RadGrid1.DataSource = null;

  if (allowRebind)
  {
    this.IsLoaded = false;
    RadGrid1.Rebind();
    return;
  }
  else
  {
    this.IsLoaded = true;
    RadGrid1.DataSource = MyDatabaseData;
    RadGrid1.MasterTableView.DataKeyNames = new string[] { MyEntity.DBFieldName.Guidfield.ToString() };
  }
}

/// <summary>
/// Populates the editable items in the row
/// </summary>
/// <param name="item"></param>
private void Populate(GridEditableItem item)
{
  if (item.ItemIndex < 0)
  {
    //inserting item so do not populate
    return;
  }

  MyEntity entity = PopulateEntity(item);

  //populates the editable items (grid)
  PopulateUIFromEntity(entity, item);
}
   
   
/// <summary>
/// Populates the entity from the database (locally cached)
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
private MyEntity PopulateEntity(GridEditableItem item)
{
  if (item.ItemIndex < 0)
  {
    //inserting item so do not populate
    return new MyEntity();
  }

  //retrieves entity data from database
  string uniqueKey = item.OwnerTableView.DataKeyValues[item.ItemIndex][MyEntity.DBFieldName.Guidfield.ToString()].ToString();
  MyEntity entity = MyEntity.GetByPrimaryKey(uniqueKey); 

  return entity;
}

   
private bool AddNewItem()
{
  int rowCount = this.MyDatabaseData.Rows.Count;

  //get required data from first row
  MyEntity originalEntity = MyEntity.DataBind(this.MyDatabaseData.Rows[0]);
  MyEntity entity = new MyEntity();
  entity.Trans = originalEntity.Trans;
  entity.SubTrans = Convert.ToString(rowCount + 1);
  bool success = entity.SaveData();

  return success;
}

 

#region Form Events
protected void Page_Load(object sender, EventArgs e)
{
}

protected void RadGrid1_NeedDataSource(object source, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
{
  if (!this.IsLoaded)
  {
    PopulateGrid(false);
  }
}

protected void RadGrid1_ItemCreated(object sender, GridItemEventArgs e)
{
  if (e.Item is GridEditableItem && e.Item.IsInEditMode)
  {
    //Populates dropdown list
    PopulateDetCodeList((GridEditableItem)e.Item);
  }
}

protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)
{
  if (e.Item is GridEditableItem && e.Item.IsInEditMode)
  {
    //Populates row data
    Populate((GridEditableItem)e.Item);
  }
}

protected void RadGrid1_ItemCommand(object source, GridCommandEventArgs e)
{
  switch (e.CommandName.ToLower())
  {
    case "initinsert":
    case "performinsert":
      //add new row in database
      ControlBase.EditSuccessful = this.AddNewItem();
      break;
    case "edit":
      ControlBase.EditSuccessful = false;
      break;
    case "update":
      //e.Canceled = !UpdateItem((GridDataItem)e.Item);

      break;
    case "cancel":
      break;
  }
}

protected void RadGrid1_PreRender(object sender, System.EventArgs e)
{
  if (!IsPostBack)
  {
    foreach (GridItem item in RadGrid1.MasterTableView.Items)
    {
      if (item is GridEditableItem)
      {
        GridEditableItem editableItem = item as GridDataItem;
        editableItem.Edit = true;
      }
    }
    RadGrid1.Rebind();
  }
}

protected void SaveButton_Click(object sender, EventArgs e)
{
  this.Save();
}

protected void CancelButton_Click(object sender, EventArgs e)
{

}   

#endregion

4 Answers, 1 is accepted

Sort by
0
Yavor
Telerik team
answered on 21 Jan 2009, 12:52 PM
Hi Kevin,

Resetting the datasource of the control at any stage of the page lifecycle is not a good practice. If you are using NeedDataSource/DataSourceControl, you can call the Rebind method for the grid, which would ensure that the most recent data would be fetched. Additionally, if you would like to alter the records shown in the grid, you can still call the Rebind method, and simply alter the select statement which would fetch the data for the control. In any case, setting the datasource to null, is not a good approach.
I hope this information helps.

Regards,
Yavor
the Telerik team

Check out Telerik Trainer, the state of the art learning tool for Telerik products.
0
PAYDAY
Top achievements
Rank 1
answered on 21 Jan 2009, 01:53 PM
"Resetting the datasource of the control at any stage of the page lifecycle is not a good practice."
I'm not sure I understand what you're saying - I've seen many posts where it is suggested to set the datasource to null prior to Rebind().  Is this not true? Can you edit my code to allow the grid to repopulate with the latest data?

NOTE: I'm not using a datasourcecontrol. I have a property that gets the data I need.

0
PAYDAY
Top achievements
Rank 1
answered on 21 Jan 2009, 02:16 PM
FYI: Here's one Telerik example suggesting setting the datasource property to null:
http://www.telerik.com/help/aspnet-ajax/grdrebindgridoncommandwithdatasourcepersistencemodenopersistence.html

0
Yavor
Telerik team
answered on 21 Jan 2009, 02:37 PM
Hello Kevin,

Indeed, this is an option, however, disabling the ViewState when performing insert/delete/update operations is not recommended. To further investigate the cause of the problem, if the issue persists, you can open a formal support ticket, and send us a small project, demonstrating your setup, as well as the unwanted behavior. I will debug it locally, and get back to you with my findings.

Sincerely yours,
Yavor
the Telerik team

Check out Telerik Trainer, the state of the art learning tool for Telerik products.
Tags
Grid
Asked by
PAYDAY
Top achievements
Rank 1
Answers by
Yavor
Telerik team
PAYDAY
Top achievements
Rank 1
Share this question
or