Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
271 views
in Technique[技术] by (71.8m points)

c# - ASP.NET: How to avoid situation that dynamically created button event refreshes the page instead of doing relevant code

(Original text updated!)

I am slowly getting into ASP.NET, currently trying to make a small webforms app for a hackathon.

The page that I am having problems with is supposed to show a list of companies to which person can apply.

Since the list of those companies can change, company always can be added or removed, I want to make some kind of table which loads values dynamically. The table appears when a user clicks "View all companies", it shows a table with each row including the name of company and a button to move to the page of this company. At this stage, I am trying to make something even more simple, for the sake of testing.

So, the button should just display some kind of text.

But here's the problem. When I click on the button, it just resets the page and as I understand, runs "Page_Load". The text is also resets to the value from Page_Load.

Now, I'll try to give code and try to give the best descriptions.

Here's the Page_Load, on first load it just displays the name of the user, and hides the table with company names. On non-first load, it should run click button events.

    protected void Page_Load(object sender, EventArgs e)
    {            
        HRGlobalHub.Code.Start.Firebase.thisFirebaseClient = new FireSharp.FirebaseClient(HRGlobalHub.Code.Start.Firebase.thisFirebaseConfig);

        pnlCompaniesView.Visible = false;

        if (!IsPostBack)
        {
            if (thisUser == null)
                lblWelcomeUser.Text = "Welcome";
            else
                lblWelcomeUser.Text = "Welcome, " + thisUser.FirstName + " " + thisUser.LastName;

            gCompany = new Code.Company.Company();
        }

        else
        {
            if (Action=="Apply")
                btnApplyClick(this, e);
            else if (Action == "Suggest")
                btnSuggestClick(this, e);
            if (Action == "View")
                btnViewClick(this, e);
        }
    }

The code for showing all companies comes here:

    protected async void btnViewAllCompanies_Click(object sender, EventArgs e)
    {
        ResetCompaniesTable();

        lblWelcomeUser.Text = "ViewAll";

        FirebaseResponse response = await HRGlobalHub.Code.Start.Firebase.thisFirebaseClient.GetTaskAsync("HRGlobalHub/Database/Companies/CompaniesList/");

        HRGlobalHub.Code.Company.CompaniesNamesList thisData = response.ResultAs<HRGlobalHub.Code.Company.CompaniesNamesList>();
        string[] CompanyArray = thisData.CompanyNameListVar.Split(',');

        for (int i = 1; i < CompanyArray.Length; i++)
        {               
            response = await HRGlobalHub.Code.Start.Firebase.thisFirebaseClient.GetTaskAsync("HRGlobalHub/Database/Companies/CompaniesDatabase/" + CompanyArray[i]);
            HRGlobalHub.Code.Company.Company result = response.ResultAs<HRGlobalHub.Code.Company.Company>();

            tbtTestTable.Rows.Add(NewCompanyRow(result));                
        }

        pnlCompaniesView.Visible = true;
        pnlCompaniesView.Width = 1100;
        tbtTestTable.Width = 1100;
        lblWelcomeUser.Text = tbtTestTable.Visible.ToString();
    }

This part loads first just the names of companies, then full companies data from the server. Each company turns into a table row. It also creates OnClientClick button events, that should load on non-first Page Load.

    public TableRow NewCompanyRow(HRGlobalHub.Code.Company.Company thisCompany) 
    {
        TableRow newRow = new TableRow();

        Button btnApply = new Button();            
        btnApply.Text = "Apply";   
        btnApply.OnClientClick +=  gCompany = thisCompany; 
        btnApply.OnClientClick += Action = "Apply";

        Button btnSuggest = new Button();
        btnSuggest.Text = "Suggest";
        btnSuggest.OnClientClick += gCompany = thisCompany;
        btnSuggest.OnClientClick += Action = "Suggest";


        Button btnView = new Button();
        btnView.Text = "View";
        btnView.OnClientClick += gCompany = thisCompany;
        btnView.OnClientClick += Action = "View";

        TableCell[] Cells = new TableCell[6];

        for (int i = 0; i < Cells.Length; i++)
            Cells[i] = new TableCell();

        Cells[0].Text = thisCompany.Name;
        Cells[1].Text = thisCompany.FieldOfWork;
        Cells[2].Text = thisCompany.Employees.Count.ToString();
        Cells[3].Controls.Add(btnView);
        Cells[4].Controls.Add(btnApply);
        Cells[5].Controls.Add(btnSuggest);

        for (int i = 0; i < Cells.Length; i++)
            Cells[i].Width = 150;

        newRow.Width = 900;

        for (int i = 0; i < Cells.Length; i++)
            newRow.Cells.Add(Cells[i]);

        btnApply.Width = 150;
        btnSuggest.Width = 150;            
        btnView.Width = 150;

        return newRow;                       
    }

Again, since it's just testing stage for this page, the button should only display the name of the company that it gets as variable.

    void btnApplyClick(Object sender, EventArgs e, HRGlobalHub.Code.Company.Company thisCompany)
    {
        lblWelcomeUser.Text = "Apply to " + thisCompany.Name;            
    }

This works but only partly: whatever I try the code from Page Load always runs the last "mentioned" Action (which is "View") and always goes for the company from the last row.

Please help me solve this!

Evgenie


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Solved it myself after all. In the end, the error was, that the dynamically created buttons also had to existe created at Page Load. So, I added the void for creating table with buttons at the Page Load, and just turned it invisible. And I also added the !PostBack proposed in comments, but on it's own it wasn't enough.

Here's where I found out about this: CommandEventArgs and Event question

However that started causing problems with buttons that needs to transit to another page. So, I added one more variable that is also checked at Page Load. If it is false, the Page works usually, if true then it moves to another page.

protected void Page_Load(object sender, EventArgs e)  
{           
HRGlobalHub.Code.Start.Firebase.thisFirebaseClient = new FireSharp.FirebaseClient(HRGlobalHub.Code.Start.Firebase.thisFirebaseConfig);  

pnlCompaniesView.Visible = false;  

if (!IsPostBack)  
{  
    if (thisUser == null)  
        lblWelcomeUser.Text = "Welcome";  
    else  
        lblWelcomeUser.Text = "Welcome, " + thisUser.FirstName + " " + thisUser.LastName;  
}  

else if (Transit == true)                  
{  
    HRGlobalHub.Pages.Company.CreateCompany.thisUser = thisUser;  
    Server.Transfer("/Pages/Company/CreateCompany.aspx", false);  
}  

else if(Transit == false)  
{           
        btnViewAllCompanies_Click(this, e);  
        pnlCompaniesView.Visible = false;  
}              
}  

Buttons are created as before, no changes here:

Button btnApply = new Button();              
btnApply.Text = "Apply";  
btnApply.Click += (sender, EventArgs) => { btnApplyClick(sender, EventArgs,    thisCompany); }; 

And the button that should transit to an other page, just changes the variable value:

    protected void btnCreateCompany_Click(object sender, EventArgs e)
    {
        Transit = true;
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...