0


Problem summary: I'm making a request to a database where I fetch created reports based on a user.

These will be listed in a table with a download button with each report where the user can download the report where that button is.

I need to know what report will be used when the button is clicked. This is where the problem is.

My solution so far won't render the asp:button - element from the StringBuilder. But if I place it in the HTML-file with just a basic input it will show.

My Code behind look like this:

SqlDataReader sqlReader = DataFromADatabaseRequest
StringBuilder table = new StringBuilder();
table.Append("<table border='1'>");
table.Append(
    "<tr>" +
    "<th>ID</th>" +
    "<th>Name</th>" +
    "<th>Prefix</th>" +
    "</tr>");
if (sqlReader.HasRows)
{
    while (sqlReader.Read())
    {
        string uniqueIdentifierToFindWhatButtonIsClicked = sqlReader["Prefix"].ToString();

        table.Append("<tr>");
        table.Append("<td>" + sqlReader["Id"] + " </td>");
        table.Append("<td>" + sqlReader["Name"] + " </td>");
        table.Append("<td> <asp:Button id="btn_" + uniqueIdentifierToFindWhatButtonIsClicked + "' class='btnDownloadFile' CommandName=" + uniqueIdentifierToFindWhatButtonIsClicked + "/> </td>");
        table.Append("</tr>");
    }
}
table.Append("</table>");

I then send this tablestring into an asp:placeholder where this table is shown. Everything works fine. But the button won't show.

If I use like a normal <input type="button" /> this works but then I can't hook a code-behind event allowing me to pass a parameter.

Thankful for all help.

Milo
  • 3,365
  • 9
  • 30
  • 44
nipple1450
  • 25
  • 4
  • 1
    You cannot create a aspnet control as a string. Create real Controls. – VDWWD Aug 02 '19 at 12:11
  • You should not generate the html in server side code but instead use GridView- or Repeater -control and use databinding to render the control with the buttons etc. – Esko Aug 02 '19 at 12:11

1 Answers1

0

.NET already has controls for dynamically generating rows with buttons on them. Take a look at the ASP Repeater items. You can also use a data grid view control with a templated column. There are numerous examples. Don't try and re-invent the wheel my friend. :)

Here is the grid view sample: How to handle click event in Button Column in Datagridview?

Note that, if you want to you can write custom code in the on item data bound if you need to handle things on a row by row basis... such as changing button text or styles or enabling controls based on a particular row's data.

Here's the row data bound technique: https://www.c-sharpcorner.com/UploadFile/1e050f/rowdatabound-event-in-gridview-in-Asp-Net/

The trick to mastering dynamic tabular data and functionality with web forms is to totally understand the controls that the .NET framework gives you.

Good luck!