Home > Blockchain >  Add asp:Buttons to table in loop?
Add asp:Buttons to table in loop?

Time:01-10

I'm looking to list entries in a table (surrounded by </asp:UpdatePanel>) and add asp:Button to each row.

Not really sure on how this can be done? Right now I'm using a StringBuilder to build the rows, but seems you can use that to add the buttons as per other questions on StackOverflow.

So, how would I do it? Should I add a control to the ? But, the control wont be rendered when I'm placing buttons in each row? Not really sure on how to approach this.

I have commented out some button code in the example that I was playing around with.

  foreach (DataRow row in dt.Rows)
                {
                    sb.Append("<tr>");
                    sb.Append($"<td>{row["plan_name"]}</td>");
                    sb.Append($"<td>{row["checklist_count"]}</td>");
                    sb.Append($"<td>{DateTime.Parse(row["next_maintenance_date"].ToString()).ToShortDateString()}</td>");
                    
                    // Buttons
                    sb.Append($"<td><span class='fa-pull-right'>");
                    sb.Append("<a href='' class='mr-2'>Details</a>");
                    sb.Append("<asp:Button CommandArgument=\"someargument\" OnClick=\"DeleteMaintenancePlan\" runat=\"server\" title=\"Test\"></asp:Button>");

                    //Button b = new Button();
                    //b.CommandArgument = row["id"].ToString();
                    //b.Click  = new EventHandler(this.DeleteMaintenancePlan);
                    //b.Text = "Some button text";
                    //sb.Append(b);
                    //divTestButtonRender.Controls.Add(b);

                    sb.Append("</span></td>");
                    sb.Append("</tr>");
                }```

Any suggestions would be more than welcome.

CodePudding user response:

I suppose you could attempt to do this, but why not just use a Listview, or a gridview?

I mean you can say have this:

        <asp:GridView ID="GHotels" runat="server" CssClass="table"
            width="50%" AutoGenerateColumns="False" DataKeyNames="ID" >
            <Columns>
                <asp:BoundField DataField="FirstName" HeaderText="FirstName"     />
                <asp:BoundField DataField="LastName" HeaderText="LastName"       />
                <asp:BoundField DataField="HotelName" HeaderText="HotelName"     />
                <asp:BoundField DataField="City" HeaderText="City"               />
                <asp:BoundField DataField="Description" HeaderText="Description" />
                <asp:TemplateField HeaderText = "Delete" ItemStyle-HorizontalAlign ="Center" >
                    <ItemTemplate>
                    <asp:Button ID="cmdDelete" runat="server" Text="Delete" 
                       CssClass="btn" 
                        OnClick="cmdDelete_Click"
                     />
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>

So, we create a grid, and also just added a plane jane asp.net button.

So, code to load is thus this:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            LoadGrid();
    }

    void LoadGrid()
    {
        using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
        {
            string strSQL = "SELECT * FROM tblHotels ORDER BY HotelName";
            using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
            {
                DataTable rstData = new DataTable;
                conn.Open();
                rstData.Load(cmdSQL.ExecuteReader());
                GHotels.DataSource = rstData;
                GHotels.DataBind();
            }
        }
    }

And we now have this:

enter image description here

And note in above, how we just dropped in a plane jane asp.net button.

When we click on that row - we can do whatever we want. But MORE important, note how we are able to get (fetch) the database PK row id, but NOT have to include/display that PK database row in the markup. This not only enhances security, but it also more practical code that can "operate" on the one given row.

And if you layout requirements are more fancy? Then use a listview.

So, the row click code for above can look like this:

we add the onclick to the button like this:

enter image description here

And now our row click event is this:

    protected void cmdDelete_Click(object sender, EventArgs e)
    {
        Button btn = sender as Button;
        GridViewRow gRow = btn.NamingContainer as GridViewRow;
        int? pkID = (int?)GHotels.DataKeys[gRow.RowIndex]["ID"];

        // do whatever to operate on row iindex
        // we have BOTH row PK value, or row index click

        string strSQL = "DELETE from tblHotels WHERE ID = "   pkID;
        using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
        {
            using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
            {
                conn.Open();
                cmdSQL.ExecuteNonQuery();
            }
        }
    }

So, in summary:

We get to hide the PK row id - not show in markup (better for security)
We can pull get the row index with ease
We can add more buttons, don't have to build messy markup in code
We did not have to write looping code

As noted, I often prefer Listviews, since you can drop in asp.net controls for each column, and not have to use "itemtemplates" over and over.

And by setting CssClass="table", I get and am using the bootstrap layout for a table (so it is responsive and re-sizes to the display rather nice too).

There might be a good case for you wanting to write loops and code out the layout of a table - but it will have to be a rather good case over using say a built in table like control of Gridview or listview.

CodePudding user response:

suggest that you use Gridview .

  •  Tags:  
  • Related