Home > Software design >  Why does the button event handler not work in C#?
Why does the button event handler not work in C#?

Time:02-03

In the HTML section, I created an "addClub" button, whenever it is clicked, two textboxes appear along with a new submit button. I created the submit button in the addClub_click method in the .cs file, however, the event handler of the submit button is not working. I tried several codes and no one is working.

Here is my code that I have created in the .cs file:

protected void AddClub_Click(object sender, EventArgs e)
{
    PlaceHolder1.Controls.Add(new LiteralControl("<br />"));
    clubname = new TextBox();
    Label cn = new Label();
    cn.Text = "Club Name ";
    PlaceHolder1.Controls.Add(cn);
    PlaceHolder1.Controls.Add(clubname);
    PlaceHolder1.Controls.Add(new LiteralControl("<br />"));
    PlaceHolder1.Controls.Add(new LiteralControl("<br />"));

    clublocation = new TextBox();
    Label cl = new Label();
    cl.Text = "Club Location ";
    PlaceHolder1.Controls.Add(cl);
    PlaceHolder1.Controls.Add(clublocation);
    PlaceHolder1.Controls.Add(new LiteralControl("<br />"));
    PlaceHolder1.Controls.Add(new LiteralControl("<br />"));

    Button Submit = new Button();
    Submit.Click  = new EventHandler(Submit_Click);
    Submit.Text = "Add";

    PlaceHolder1.Controls.Add(Submit);
    PlaceHolder1.Controls.Add(new LiteralControl("<br />"));
}           
    
protected void Submit_Click(object sender, EventArgs e)
{
    Response.Write("Completed successfully");
}

Edit

I performed several other trials and I kind of discovered where is the problem. Whenever I move the code of the Submit button to the page_load section, the eventhandler works; thus the problem is in creating the button and adding to it the eventhandler within the addClub_click method. However I couldn't find a solution to that. Does anyone know how to perform that?

CodePudding user response:

replace

Submit.Click  = new EventHandler(Submit_Click);

with

Submit.Click  = Submit_Click;

CodePudding user response:

I think you need to back up the truck here somewhat.

You looking and thinking of this as a user interface problem, when in fact this is "more" of a data problem.

I mean, after you add that "row" of data, then what?

Do you plan THEN to somehow grab, get, gather that information and save it into a database? or when you leave the page, all data is gone?

And WHY oh why would you try to write code in a page for repeating data?

One of the "greatest" strengths of webforms is its ability to repeat data, and do so WITHOUT even having to write loops!

You need/want to think of this problem as a data management problem.

In 99 out of a 100 problems?

If you writing code to inject controls into a page, YOU DOING IT WRONG! You just are!!

I mean, after you inject all those controls, how you going to come back and edit that data? Too much pain.

I mean, after you inject all those controls, how you going to come back and even simple display that data? Too much pain!

Don't, just don't go down this road, it is the WRONG road, and wrong approach. You will forever more be attempting to maintain this code, not able to re-use that code for editing "existing" data, and at the end of the day, you will have achieved some working code of VERY LITTLE value.

Webforms is "bristling" with boatloads of controls that will do this dirty work of repeating data for you. webforms has a whole bunch of controls that will do all this work for you, but BETTER means it can also display the data. In in 09 out 10 cases:

You don't have to write loops for such code.
You don't have to try and write code to inject controls
You have all kinds of fantastic built in events to do heavy lifting for you.
Such controls are "data aware", and you reduce both markup you have to write, and code.

Be it a repeater, listview, girdview and more?

Let the asp.net system do all this dirty work for you.

Let the poor saps writing PHP or using mvc write all that silly looping code in their markup, and create world poverty while they are at this.

And MORE important, for the "same" amount of work, you write less code, and that code gives you full data base operations.

Lets do an example:

Lets toss some text boxes - say some to enter hotel infomration.

Then lets add a "save" button, send the one row to a data base, and then display the results (in a grid view).

So, we have this:

<h3>Add Hotels</h3>
<div id="EditRecord" runat="server" style="float: left;padding: 15px; border:solid">
    <div style="float: left" >
        <label>HotelName</label>
        <asp:TextBox ID="txtHotel" runat="server" Width="280" f="HotelName" /><br />
        <label>First Name</label>
        <asp:TextBox ID="tFN" runat="server" Width="140"  f="FirstName"/><br />
        <label>Last Name</label>
        <asp:TextBox ID="tLN" runat="server" Width="140" f="LastName" /><br />
        <label>City</label>
        <asp:TextBox ID="tCity" runat="server" Width="140" f="City" /><br />
    </div>
    <div style="float: left; margin-left: 20px" >
        <label>Description</label>
        <br />
        <asp:TextBox ID="txtNotes" runat="server" Width="400" TextMode="MultiLine"
            Height="150px" f="Description"></asp:TextBox><br />
    </div>
    <div style="clear: both"></div>
    <button id="cmdSave" runat="server"  type="button"
        onserverclick="cmdSave_Click">
        <span aria-hidden="true" >Save</span>
    </button>
</div>

So far, really drag drop in the desinger.

So, our code to load (when we come back to edit the data) is this:

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

    void LoadData()
    {
        string strSQL = "SELECT * FROM tblHotelsE ORDER BY HotelName";
        DataTable rstData = General.MyRst(strSQL);
        GridView1.DataSource = rstData;
        GridView1.DataBind();
        ViewState["PKID"] = 0;
    }

And that save/add button code is this:

protected void cmdSave_Click(object sender, EventArgs e)
{
    int PKID = (int)ViewState["PKID"];
    General.FWriter(this.EditRecord, PKID, "tblHotelsE");
    General.FClear(this.EditRecord);
    LoadData();  // re-load grid to show any changes
}

And our edit the data again button is this:

protected void cmdEdit_Click(object sender, EventArgs e)
{
    HtmlButton btn = sender as HtmlButton;
    GridViewRow gRow = btn.NamingContainer as GridViewRow;
    int PKID = (int)GridView1.DataKeys[gRow.RowIndex]["ID"];
    ViewState["PKID"] = PKID;

    string strSQL = $"SELECT * FROM tblHotelsE WHERE ID = {PKID}";
    DataRow rstData = General.MyRst(strSQL).Rows[0];
    General.FLoader(this.EditRecord, rstData);

}

So, no "injecting" of controls is required.

The end result looks like this:

enter image description here

Note carefull.

We can add 1 or 20 rows - we DO NOT have to write code to create controls, inject controls.

Now, I can post some of the helper routines (floader, fwriter). That does does loop the controls, and load from/to the database, but at the end of the day?

don't try and inject controls for repeating data - it simply not the way how webforms works.

Do things the web forms way, and you wind up with less effort, less code, and not have to write code to inject controls to display repeating data.

  • Related