将新记录添加到Telerik RadGrid

本文关键字:Telerik RadGrid 添加 新记录 | 更新日期: 2023-09-27 17:56:27

我有以下Telerik RadGrid,我在C#中使用:

<MasterTableView Width="100%" EditMode= "InPlace" ClientDataKeyNames="menuID" CommandItemDisplay= "Top">
    <Columns>
        <telerik:GridBoundColumn DataField="Name" HeaderText="Name" SortExpression="Name" UniqueName="Name"></telerik:GridBoundColumn>
        <telerik:GridTemplateColumn UniqueName="Type" HeaderText="Type">
            <ItemTemplate>
                <asp:TextBox ID="Type" Text='<%# DataBinder.Eval(Container.DataItem, "Type") %>' runat="server"></asp:TextBox>
            </ItemTemplate>
            <EditItemTemplate>
            </EditItemTemplate>
        </telerik:GridTemplateColumn>
        <telerik:GridTemplateColumn UniqueName="List" HeaderText="List">
            <ItemTemplate>
                <asp:CheckBox ID="List" runat="server" Checked='<%# DataBinder.Eval(Container.DataItem, "List") %>' />
            </ItemTemplate>
            <EditItemTemplate>
            </EditItemTemplate>
        </telerik:GridTemplateColumn>
        <telerik:GridTemplateColumn UniqueName="loadAtStart" HeaderText="loadAtStart">
            <ItemTemplate>
                <asp:CheckBox ID="loadAtStart" runat="server" Checked='<%# DataBinder.Eval(Container.DataItem, "loadAtStart") %>' />
            </ItemTemplate>
            <EditItemTemplate>
            </EditItemTemplate>
        </telerik:GridTemplateColumn>
    </Columns>
</MasterTableView>

网格中填充了数据,并在编辑数据时正常工作。

但是当我单击 Telerik 提供的"添加新记录"按钮时,会添加一个空行,在列中没有任何文本框或复选框,以便在添加的新行中进行编辑。这只是一个空行。我认为我必须在调用的 ItemDataBound 事件中动态创建控件,但我没有设法找到实际的代码。

我该如何解决这个问题?

将新记录添加到Telerik RadGrid

请尝试使用以下代码片段。

.ASPX

<telerik:RadGrid ID="RadGrid1" runat="server" AutoGenerateColumns="false" OnNeedDataSource="RadGrid1_NeedDataSource"
    AllowFilteringByColumn="true" AllowPaging="true" OnItemCommand="RadGrid1_ItemCommand">
    <PagerStyle AlwaysVisible="true" />
    <MasterTableView DataKeyNames="UniqueID" CommandItemDisplay="Top">
        <Columns>
            <telerik:GridBoundColumn DataField="ID" UniqueName="ID" HeaderText="ID">
            </telerik:GridBoundColumn>
            <telerik:GridTemplateColumn>
                <ItemTemplate>
                    <asp:TextBox ID="TextBox1" runat="server" Text='<%# Eval("Name") %>'></asp:TextBox>
                </ItemTemplate>
            </telerik:GridTemplateColumn>
        </Columns>
    </MasterTableView>
</telerik:RadGrid>
<asp:Button ID="Button1" runat="server" Text="Save All" OnClick="Button1_Click" />

ASPX.CS

public partial class aaaa : System.Web.UI.Page
{
    public List<Employee> lstEmployee
    {
        get
        {
            if (Session["lstEmployee"] != null)
            {
                return (List<Employee>)Session["lstEmployee"];
            }
            else
            {
                return new List<Employee>();
            }
        }
        set
        {
            Session["lstEmployee"] = value;
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            List<Employee> list = new List<Employee>();
            Employee obj = new Employee();
            obj.ID = 1;
            obj.Name = "Name1";
            obj.UniqueID = Guid.NewGuid();
            list.Add(obj);
            obj = new Employee();
            obj.ID = 2;
            obj.Name = "Name2";
            obj.UniqueID = Guid.NewGuid();
            list.Add(obj);
            lstEmployee = list;
        }
    }
    protected void RadGrid1_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
    {
        RadGrid1.DataSource = lstEmployee;
    }
    protected void RadGrid1_ItemCommand(object sender, GridCommandEventArgs e)
    {
        if (e.CommandName == RadGrid.InitInsertCommandName)
        {
            saveAllData();
            lstEmployee.Insert(0, new Employee() { UniqueID = Guid.NewGuid() });
            e.Canceled = true;
            RadGrid1.Rebind();
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        saveAllData();
    }
    protected void saveAllData()
    {
        //Update Session
        foreach (GridDataItem item in RadGrid1.MasterTableView.Items)
        {
            Guid UniqueID = new Guid(item.GetDataKeyValue("UniqueID").ToString());
            Employee emp = lstEmployee.Where(i => i.UniqueID == UniqueID).First();
            emp.Name = (item.FindControl("TextBox1") as TextBox).Text;
        }
    }
}
public class Employee
{
    public Guid UniqueID { get; set; }
    public int ID { get; set; }
    public string Name { get; set; }
    public bool IsActive { get; set; }
    public int weeknumber { get; set; }
}
   我根据我的要求修改了参数,还包括所有 CURD 操作。

ASPX 页

  <telerik:RadGrid ID="RadGrid1" runat="server" AutoGenerateColumns="false"
                OnNeedDataSource="RadGrid1_NeedDataSource"
                AllowFilteringByColumn="true" AllowPaging="true" OnItemCommand="RadGrid1_ItemCommand">
                <PagerStyle AlwaysVisible="true" />
                <MasterTableView DataKeyNames="UniqueID" CommandItemDisplay="Top" AutoGenerateColumns="false" >
                    <Columns>
                        <telerik:GridEditCommandColumn ButtonType="FontIconButton" />
                        <telerik:GridButtonColumn CommandName="Delete" Text="Delete" ButtonType="FontIconButton" UniqueName="DeleteColumn" />
                        <telerik:GridBoundColumn DataField="ID" UniqueName="ID" HeaderText="ID">
                        </telerik:GridBoundColumn>
                        <telerik:GridTemplateColumn  DataField="Sku" UniqueName="Sku" HeaderText="Sku">
                            <ItemTemplate>
                                <asp:Label ID="TxtSku" runat="server" Text='<%# Eval("Sku") %>'></asp:Label>
                            </ItemTemplate>
                            <EditItemTemplate>
                                <asp:TextBox ID="TxtSku" runat="server" Text='<%# Eval("Sku") %>'></asp:TextBox>
                            </EditItemTemplate>
                            <InsertItemTemplate>
                                <asp:TextBox ID="TxtSku" runat="server" Text='<%# Eval("Sku") %>'></asp:TextBox>
                            </InsertItemTemplate>
                        </telerik:GridTemplateColumn>                           
                    </Columns>                        
                </MasterTableView>
            </telerik:RadGrid>
            <asp:Button ID="Button1" runat="server" Text="Save All" OnClick="Button1_Click" />
           <telerik:RadAjaxManager runat="server">
            <AjaxSettings>
                <telerik:AjaxSetting AjaxControlID="RadGrid1">
                    <UpdatedControls>
                        <telerik:AjaxUpdatedControl ControlID="RadGrid1" />
                        <telerik:AjaxUpdatedControl ControlID="Button1" />
                    </UpdatedControls>
                </telerik:AjaxSetting>
            </AjaxSettings>
        </telerik:RadAjaxManager>
            <telerik:RadAjaxLoadingPanel ID="RadAjaxLoadingPanel1" runat="server">
            </telerik:RadAjaxLoadingPanel>

CS 代码

    public List<ItemDetail> ItemDetail
    {
        get
        {
            if (Session["ItemDetail"] != null)
            {
                return (List<ItemDetail>)Session["ItemDetail"];
            }
            else
            {
                return new List<ItemDetail>();
            }
        }
        set
        {
            Session["ItemDetail"] = value;
        }
    }
    protected void RadGrid1_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
    {
        RadGrid1.DataSource = ItemDetail;
    }
    protected void RadGrid1_ItemCommand(object sender, GridCommandEventArgs e)
    {
        if (e.CommandName == RadGrid.InitInsertCommandName)
        {
        }
        if (e.CommandName == RadGrid.PerformInsertCommandName)
        {
            var item = (GridEditFormItem)e.Item;
            var txtReferenceNumber = (TextBox)item.FindControl(id: "TxtSku");
            var val = txtReferenceNumber.Text;
            ItemDetail.Insert(0, new ItemDetail() { UniqueID = Guid.NewGuid(), Sku = val, ID = Convert.ToInt32(22) });
            item.Edit = false;
            RadGrid1.Rebind();
        }
        if (e.CommandName == RadGrid.UpdateCommandName)
        {
            var item = (GridEditFormItem)e.Item;
            var txtReferenceNumber = (TextBox)item.FindControl(id: "TxtSku");
            string requestId = item.GetDataKeyValue(keyName: "UniqueID").ToString().Trim();
            Guid RequestIndentifier = Guid.Parse(requestId);
            var val = txtReferenceNumber.Text;
            var itemFind = ItemDetail.Where(x => x.UniqueID == RequestIndentifier);
            itemFind.FirstOrDefault().Sku = val;
            item.Edit = false;
            RadGrid1.Rebind();
        }
        if (e.CommandName == RadGrid.DeleteCommandName)
        {
            var item = (GridDataItem)e.Item;
            string requestId = item.GetDataKeyValue(keyName: "UniqueID").ToString().Trim();
            Guid RequestIndentifier = Guid.Parse(requestId);
            ItemDetail.RemoveAll(x => x.UniqueID == RequestIndentifier);
            RadGrid1.Rebind();
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        SaveAllData();
    }
    private void SaveAllData()
    {
        //Update Session
        foreach (GridDataItem item in RadGrid1.MasterTableView.Items)
        {
            Guid UniqueID = new Guid(item.GetDataKeyValue("UniqueID").ToString());
            ItemDetail emp = ItemDetail.Where(i => i.UniqueID == UniqueID).First();
            emp.Sku = (item.FindControl("TxtSku") as TextBox).Text;
        }
    }

}
public class ItemDetail
{
    public Guid UniqueID { get; set; }
    public int ID { get; set; }
    public string Sku { get; set; }      
}

 if (!Page.IsPostBack)
            {                    
                List<ItemDetail> list = new List<ItemDetail>();
                ItemDetail obj = new ItemDetail
                {
                    ID = 1,
                    Sku = "Name1",
                    UniqueID = Guid.NewGuid()
                };
                list.Add(obj);
                obj = new ItemDetail();
                obj.ID = 2;
                obj.Sku = "Name2";
                obj.UniqueID = Guid.NewGuid();
                list.Add(obj);
                ItemDetail = list;
            }
希望这会对您有所帮助:-)

我真的不喜欢这些解决方案中的任何一个,因为它们需要使用会话。 会话有它的位置,但我相信它更多地被用作拐杖。

由于回发,您已经通过 ViewState 将 RadGrid 信息发送回服务器端,因此为什么不使用它的信息而不是依赖内存中存储。

在网格中添加和删除项的示例。 是的,它确实需要迭代项目来重建列表,但它是会话的替代方案,所以我相信它有优点。

protected void addValueToRecentTagList(string text)
{
    List<string> items = new List<string>();
    foreach(GridDataItem row in RadGridNewTags.Items)
        items.Add(row["tag"].Text);
    items.Add(text);
    RadGridNewTags.DataSource = items;
    RadGridNewTags.DataBind();
}
protected void removeValueFromRecentTagList(string text)
{
    List<string> items = new List<string>();
    bool rebind = false;
    
    foreach (GridDataItem row in RadGridNewTags.Items)
    {
        if (row["tag"].Text == text)
            rebind = true;
        else
            items.Add(row["tag"].Text);
    }
    if (rebind)
    {
        RadGridNewTags.DataSource = items;
        RadGridNewTags.DataBind();
    }
}

您必须在 EditItemTemplate 中插入一个控件才能在"编辑"或"插入"模式下显示。

或者,您可以添加一个插入项模板并在其中放置一个控件:

<telerik:GridTemplateColumn UniqueName="loadAtStart" HeaderText="loadAtStart">
        <ItemTemplate>
            <asp:CheckBox ID="loadAtStart" runat="server" Checked='<%# DataBinder.Eval(Container.DataItem, "loadAtStart") %>' />
        </ItemTemplate>
        
        <EditItemTemplate>
           <asp:CheckBox ID="cbxEditLoadAtStart" runat="server" Checked='<%# Bind("loadAtStart") %>' />
        </EditItemTemplate>
        <InsertItemTemplate>
            <asp:CheckBox ID="cbxInsertLoadAtStart" runat="server" />
        </InsertItemTemplate>
    </telerik:GridTemplateColumn>