locked
Add new distinct Row to DataTable and display in GridView using C# and ASP.Net RRS feed

  • Question

  • User-1453200658 posted

    Hi,

    I am working on a project in asp.net with c#.

    I take data from mysql database and with this data set populate GridView

    I want to dynamically generate a new Row in GridView respecting the sequence of the column sID_contents

    For example in GV I have:

    '- Set n.2', 2, 'D1C', 4
    'Management 2', 2, 'D1C', 5
    'Miss 2', 2, 'D1C', 6
    

    I need insert new row on sID_contents equal to 2

    '- Set n.2', 2, 'D1C', 4
    'Management 2', 2, 'D1C', 5
    'Miss 2', 2, 'D1C', 6
    'New row Thread 2', 2, 'D1C', 10
    

    The new row is

    'New row Thread 2', 2, 'D1C', 10
    

    and must be displayed along with all lines where sID_contents equal to 2

    This is my data

    -- ----------------------------
    -- Table structure for t_contents
    -- ----------------------------
    DROP TABLE IF EXISTS `t_contents`;
    CREATE TABLE `t_contents`  (
      `contents` varchar(1000) DEFAULT NULL,
      `sID_contents` int(11) DEFAULT NULL,
      `sUnita` varchar(255) DEFAULT NULL,
      `sID` int(11) NOT NULL AUTO_INCREMENT,
      PRIMARY KEY (`sID`) USING BTREE,
      UNIQUE INDEX `contents`(`contents`) USING BTREE
    ) ENGINE = InnoDB;
     
    -- ----------------------------
    -- Records of t_contents
    -- ----------------------------
    INSERT INTO `t_contents` VALUES ('- Set n.1', 1, 'D1C', 1);
    INSERT INTO `t_contents` VALUES ('Management', 1, 'D1C', 2);
    INSERT INTO `t_contents` VALUES ('Miss', 1, 'D1C', 3);
     
    INSERT INTO `t_contents` VALUES ('- Set n.2', 2, 'D1C', 4);
    INSERT INTO `t_contents` VALUES ('Management 2', 2, 'D1C', 5);
    INSERT INTO `t_contents` VALUES ('Miss 2', 2, 'D1C', 6);
     
    INSERT INTO `t_contents` VALUES ('- Set n.3', 3, 'D1C', 7);
    INSERT INTO `t_contents` VALUES ('Management 3', 3, 'D1C', 8);
    INSERT INTO `t_contents` VALUES ('Miss 3', 3, 'D1C', 9);
    

    This is my code behind

    public partial class gv : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                DataTable dt = new DataTable();
                dt.Columns.AddRange(new DataColumn[]
                {
                       new DataColumn("contents"),
                       new DataColumn("sID_contents"),
                       new DataColumn("sUnita"),
                       new DataColumn("sID")
                });
      
                dt.Rows.Add("- Set n.1", 1, "D1C", 1);
                dt.Rows.Add("Management", 1, "D1C", 2);
                dt.Rows.Add("Miss", 1, "D1C", 3);
      
                dt.Rows.Add("- Set n.2", 2, "D1C", 4);
                dt.Rows.Add("Management 2", 2, "D1C", 5);
                dt.Rows.Add("Miss 2", 2, "D1C", 6);
      
                dt.Rows.Add("- Set n.3", 3, "D1C", 7);
                dt.Rows.Add("Management 3", 3, "D1C", 8);
                dt.Rows.Add("Miss 3", 3, "D1C", 9);
      
                gvitems.DataSource = dt;
                gvitems.DataBind();
            }
        }
    
        protected void gvProducts_RowDataBound(object sender, GridViewRowEventArgs e)
        {        
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                    string lbset = (string)DataBinder.Eval(e.Row.DataItem, HttpUtility.HtmlDecode("contents"));
                   
                    if (lbset.ToString().StartsWith("- Set "))
                    {
                        ImageButton image = new ImageButton();
                        image.ImageUrl = "img/add-page-red.gif";
                        image.ToolTip = "Add new row to " + HttpUtility.HtmlDecode(lbset)
                            .ToString()
                            .Replace("<h4><strong>", "")
                            .Replace("</strong></h4>", "");
                        e.Row.Cells[2].Controls.Add(image);
                    }
            }
        }
    }
    Friday, March 19, 2021 8:53 PM

Answers

  • User-939850651 posted

    Hi Edward Sheriff Curtis,

    According to your description, if you want to insert data into datatable dynamically, you could add Event handler to ImageButton, but when dynamically adding controls to an ASP.NET page in runtime the object references are lost at postback because they have no handle in the codebehind, so you need to creat them again in Page_Load().

    Here is my test:

    public static DataTable dt = new DataTable();
            protected void Page_Load(object sender, EventArgs e)
            {
                if (!Page.IsPostBack)
                {
                    dt.Columns.AddRange(new DataColumn[] { 
                        new DataColumn("contents", typeof(string)),
                        new DataColumn("sID_contents", typeof(int)),
                        new DataColumn("sUnita", typeof(string)),
                        new DataColumn("sID", typeof(int))
                        });
    
                    dt.Rows.Add("- Set n.1", 1, "D1C", 1);
                    dt.Rows.Add("Management", 1, "D1C", 2);
                    dt.Rows.Add("Miss", 1, "D1C", 3);
    
                    dt.Rows.Add("- Set n.2", 2, "D1C", 4);
                    dt.Rows.Add("Management 2", 2, "D1C", 5);
                    dt.Rows.Add("Miss 2", 2, "D1C", 6);
    
                    dt.Rows.Add("- Set n.3", 3, "D1C", 7);
                    dt.Rows.Add("Management 3", 3, "D1C", 8);
                    dt.Rows.Add("Miss 3", 3, "D1C", 9);
    
                    gvitems.DataSource = dt;
                    gvitems.DataBind();
                }
                else {
                    this.addControls();
                }
            }
    
            private void addControls()
            {
                foreach (GridViewRow row in gvitems.Rows) {
                    
                    string lbset = (row.Cells[0].FindControl("contents")as Label).Text;
                    if (lbset.ToString().StartsWith("- Set "))
                    {
                        ImageButton image = new ImageButton();
                        image.ID = "AddRow";
                        image.ImageUrl = "img/add.png";
                        image.ToolTip = "Add new row to " + HttpUtility.HtmlDecode(lbset)
                            .ToString()
                            .Replace("<h4><strong>", "")
                            .Replace("</strong></h4>", "");
                        image.Click += new ImageClickEventHandler(addRow_Click);
                        row.Cells[2].Controls.Add(image);
                    }
                }
            }
    
            protected void gvProducts_RowDataBound(object sender, GridViewRowEventArgs e)
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    string lbset = (string)DataBinder.Eval(e.Row.DataItem, HttpUtility.HtmlDecode("contents"));
    
                    if (lbset.ToString().StartsWith("- Set "))
                    {
                        ImageButton image = new ImageButton();
                        image.ID = "AddRow";
                        image.ImageUrl = "img/add.png";
                        image.ToolTip = "Add new row to " + HttpUtility.HtmlDecode(lbset)
                            .ToString()
                            .Replace("<h4><strong>", "")
                            .Replace("</strong></h4>", "");
                        e.Row.Cells[2].Controls.Add(image);
                    }
                }
            }
    
            protected void addRow_Click(object sender, ImageClickEventArgs e)
            {
                ImageButton imgBtn = (ImageButton)sender;
                char last = imgBtn.ToolTip[imgBtn.ToolTip.Length - 1];
                int sID_contents = int.Parse(last.ToString());
                dt.Rows.Add("New row Thread "+ sID_contents.ToString(), sID_contents, "D1C", gvitems.Rows.Count+1);
                DataTable newDataTable = dt.AsEnumerable()
                       .OrderBy(r => r.Field<int>("sID_contents"))
                       .ThenBy(r => r.Field<int>("sID"))
                       .CopyToDataTable();
                gvitems.DataSource = newDataTable;
                gvitems.DataBind();
            }
    <asp:GridView runat="server" ID="gvitems" AutoGenerateColumns="false" OnRowDataBound="gvProducts_RowDataBound">
                    <Columns>
                        <asp:TemplateField HeaderText="Header1">
                            <ItemTemplate>
                                <asp:Label Text='<%#Eval("contents") %>' ID="contents" runat="server" />
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Header2">
                            <ItemTemplate>
                                <asp:Label Text='<%#Eval("sID_contents") %>' runat="server" />
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Header3">
                            <ItemTemplate>
                                <asp:Label Text='<%#Eval("sUnita") %>' runat="server" />
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Header4">
                            <ItemTemplate>
                                <asp:Label Text='<%#Eval("sID") %>' runat="server" />
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                </asp:GridView>

    Result:

    Hope this can help you.

    Best regards,

    Xudong Peng

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, March 22, 2021 7:54 AM