-1

I'm creating programmatically event(s) when a dropdownlist SelectedIndexChanged. Now that's not working but i think it has something todo with the postback but all the rest is working so far.

Adding a new row and storing the value of the previous row are working fine. I don't find a working solution for my programmatically created event(s).

My code is like this =>

    static List<TableRow> TableRows = new List<TableRow>();


    protected void Page_Load(object sender, EventArgs e)
    {
            string vorigePagina = Request.UrlReferrer.ToString();

            //Controleer of de pagina gerefreshd werd of voor het eerst geladen wordt.
            if (!vorigePagina.Contains("FactuurToevoegen.aspx"))
            {
                //Als de pagina voor de eerste keer geladen wordt moet de tabel leeggemaakt worden.
                TableRows.Clear();
            }

            //Response.Write(TableRows.Count.ToString());

            //if (TableRows != null)
            //{
            foreach (TableRow row in TableRows)
            {
                tblArtikels.Rows.Add(row);
            }
    )

    public void RijToevoegen()
    {
        try
        {

            if (Factuur.artikelTeller == null && tblArtikels.Rows.Count != null)
            {
                Factuur.artikelTeller = 0;
            }
            else if (Factuur.artikelTeller != 0 && tblArtikels.Rows.Count != 0)
            {
                Factuur.artikelTeller = Factuur.artikelTeller + 1;
            }
            else
            {
                Factuur.artikelTeller = Factuur.artikelTeller + 1;
            }

            int artikelTeller = Factuur.artikelTeller;

            //Alle data halen uit de PassThrough class om opnieuw een connectie te maken met SharePoint
            contextToken = PassThrough.contextToken;
            sharepointUrl = PassThrough.sharepointUrl;
            accessToken = PassThrough.accessToken;
            ClientContext clientContext = TokenHelper.GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken);

            //Dynamisch de rijen aanmaken met de producten waar het aantal, artikel, prijs en btw worden weergegeven.
            TableRow row = new TableRow();
            TableCell cell1 = new TableCell();
            TableCell cell2 = new TableCell();
            TableCell cell3 = new TableCell();
            TableCell cell4 = new TableCell();
            TextBox txtArtikelAantal = new TextBox();
            TextBox txtArtikel = new TextBox();
            TextBox txtArtikelPrijs = new TextBox();
            TextBox txtArtikelBTWPercentage = new TextBox();

            DropDownList ddlArtikel = new DropDownList();
            ddlArtikel.AutoPostBack = true;
            ddlArtikel.Width = 180;
            ddlArtikel.SelectedIndexChanged += new EventHandler(ddlArtikel_SelectedIndexChanged);
            ddlArtikel.EnableViewState = true;

            //Breedte instellen van de textboxes en td's (cellen)
            txtArtikelAantal.Width = 50;
            txtArtikelPrijs.Width = 100;
            txtArtikelBTWPercentage.Width = 50;
            cell1.Width = 120;
            cell2.Width = 364;
            cell3.Width = 180;
            cell4.Width = 60;
            cell4.HorizontalAlign = HorizontalAlign.Right;

            row.ID = "row_" + artikelTeller;
            cell1.ID = "Cell1_" + artikelTeller;
            cell2.ID = "Cell2_" + artikelTeller;
            cell3.ID = "Cell3_" + artikelTeller;
            cell4.ID = "Cell4_" + artikelTeller;
            txtArtikelAantal.ID = "txtArtikelAantal_" + artikelTeller;
            txtArtikel.ID = "txtArtikel_" + artikelTeller;
            txtArtikelPrijs.ID = "txtArtikelPrijs_" + artikelTeller;
            txtArtikelPrijs.Enabled = false;
            txtArtikelBTWPercentage.ID = "txtArtikelBTWPercentage_" + artikelTeller;
            txtArtikelBTWPercentage.Visible = true;
            ddlArtikel.ID = "ddlArtikel_" + artikelTeller;

            cell1.Controls.Add(txtArtikelAantal);
            cell2.Controls.Add(ddlArtikel);
            cell3.Controls.Add(txtArtikelPrijs);
            cell4.Controls.Add(txtArtikelBTWPercentage);

            //Lijst met artikelen ophalen en dropdown opvullen
            List oListArtikels = clientContext.Web.Lists.GetByTitle("Lijst artikels");

            clientContext.ExecuteQuery();


            CamlQuery cQArtikels = new CamlQuery();
            cQArtikels.ViewXml = "<View>"
            + "<Query>"
            + "<OrderBy><FieldRef Name='arArtikelOmschrijving'/></OrderBy>"
            + "</Query>"
            + "</View>";

            Microsoft.SharePoint.Client.ListItemCollection artikelListItem = oListArtikels.GetItems(cQArtikels);

            clientContext.Load(artikelListItem);

            clientContext.ExecuteQuery();


            foreach (Microsoft.SharePoint.Client.ListItem artikelItem in artikelListItem)
            {
                string artikelOmschrijving = artikelItem["arArtikelomschrijving"].ToString();
                string artikelPrijsExclBTW = string.Format("{0:0.00}", artikelItem["arBasisprijsExclBTW"].ToString());

                ddlArtikel.Items.Add(new System.Web.UI.WebControls.ListItem(artikelOmschrijving + " (" + artikelPrijsExclBTW + ")", artikelPrijsExclBTW));

                txtArtikelAantal.Text = "1";
                txtArtikelPrijs.Text = string.Format("{0:0.00}", double.Parse(artikelPrijsExclBTW).ToString());

                txtArtikelBTWPercentage.Text = double.Parse((artikelItem["arBTWcode"] as FieldLookupValue).LookupValue).ToString() + "%";
            }

            txtArtikelPrijs.Text = (double.Parse(txtArtikelAantal.Text) * double.Parse(txtArtikelPrijs.Text)).ToString();


            row.Cells.Add(cell1);
            row.Cells.Add(cell2);
            row.Cells.Add(cell3);
            row.Cells.Add(cell4);
            tblArtikels.Rows.Add(row);
            TableRows.Add(row);
        }
        catch (Exception ex)
        {
            Response.Write("Foutbericht artikels: " + ex.Message);
        }
    }

    protected void ddlArtikel_SelectedIndexChanged(object sender, EventArgs e)
    {

        try
        {
            txtTotaalinclBTW.Text = "125";
            Response.Write("Artikel Changed !!!");
        }
        catch (Exception ex)
        {
            Response.Write("Foutbericht Artikelchanged: " + ex.Message);
        }
    }
  • 2
    Please, clarify what do you mean by "not working". Are you getting some exception? What exactly line of your code throwing it? – Andrey Korneyev Dec 29 '14 at 10:46
  • I mean the event is not putting back any data. as requested here => protected void ddlArtikel_SelectedIndexChanged(object sender, EventArgs e) { try { txtTotaalinclBTW.Text = "125"; Response.Write("Artikel Changed !!!"); } catch (Exception ex) { Response.Write("Foutbericht Artikelchanged: " + ex.Message); } } – user3512855 Dec 29 '14 at 11:00
  • I can understand dutch, but many others don't, A suggestion for you: write your code in english :) – CularBytes Dec 29 '14 at 11:02

2 Answers2

0

It sounds like your not posting back to the server. As per this answer (DropDownList doesn't postback on SelectedIndexChanged) you have to enable autopostback on the control on your page for this to happen

Community
  • 1
  • 1
Matt
  • 81
  • 1
  • 6
  • Well i'm setting here the autopostback => DropDownList ddlArtikel = new DropDownList(); ddlArtikel.AutoPostBack = true; – user3512855 Dec 29 '14 at 10:58
  • @user3512855 if you put a breakpoint in your event handler does it get hit? if not, then the page is not posting back. Could you expand your question to show the html you are using for the control and what you mean by its not working? – Matt Dec 29 '14 at 11:00
  • That function protected void ddlArtikel_SelectedIndexChanged(object sender, EventArgs e) { try { txtTotaalinclBTW.Text = "125"; Response.Write("Artikel Changed !!!"); } catch (Exception ex) { Response.Write("Foutbericht Artikelchanged: " + ex.Message); } } isn't doing anything. – user3512855 Dec 29 '14 at 11:03
  • I'm loading that function here ddlArtikel.SelectedIndexChanged += new EventHandler(ddlArtikel_SelectedIndexChanged); – user3512855 Dec 29 '14 at 11:04
  • is getting hit but not doing anything, or isn't getting hit? – Matt Dec 29 '14 at 11:04
  • can you try writing out your response to a textbox OR use an update panel and replace the content of the panel, sounds like its trying to replace a lot more (response.write). – Matt Dec 29 '14 at 11:12
  • the problem is something with the id of the dynamic created dropdownlists. – user3512855 Dec 29 '14 at 13:47
  • well i checked again and the postback isn't doing anything. So the protected void ddlArtikel_SelectedIndexChanged(object sender, EventArgs e){ ... function isn't called. – user3512855 Dec 29 '14 at 14:54
  • @user3512855 that was my first question. Sounds like your control is not posting back to the server. If you are adding the dropdown control to the page programmatically can you try doing it using HTML instead. can you update your original question with the code that you use so I can see it, or put it up on GitHub? – Matt Dec 29 '14 at 16:53
0

Well i tried an example i found on the web with postback and dynamic created controls. It's working for textboxes and checkboxes but not for my events i'm creating. See my example below. My event is not getting fired. =>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace testDebugger
{
public partial class WebForm1 : System.Web.UI.Page
{
    private int numOfRows = 1;

    protected void Page_Load(object sender, EventArgs e)
    {
        //Generate the Rows on Initial Load
        if (!Page.IsPostBack)
        {
            GenerateTable(numOfRows);
        }
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        if (ViewState["RowsCount"] != null)
        {
            numOfRows = Convert.ToInt32(ViewState["RowsCount"].ToString());
            GenerateTable(numOfRows);
        }
    }

    protected void Button2_Click(object sender, EventArgs e)
    {
        GetSelectedRows();
    }

    private void SetPreviousData(int rowsCount, int colsCount)
    {
        Table table = (Table)Page.FindControl("Table1");
        if (table != null)
        {
            for (int i = 0; i < rowsCount; i++)
            {
                for (int j = 0; j < colsCount; j++)
                {
                    if (j == 0)
                    {
                        //Get the Checked value of the CheckBox using the Request objects
                        string check = Request.Form["CheckBoxRow_" + i + "Col_" + j];
                        //Extract the CheckBox Control from within the Table
                        CheckBox cb = (CheckBox)table.Rows[i].Cells[j].FindControl("CheckBoxRow_" + i + "Col_" + j);
                        if (check == "on") //If selected
                        {
                            cb.Checked = true;
                        }
                    }
                    else if (j == 1)
                    {
                        DropDownList ddl = (DropDownList)table.Rows[i].Cells[j].FindControl("DropDown_" + i + "Col_" + j);
                        ddl.SelectedValue = Request.Form["DropDown_" + i + "Col_" + j];
                    }
                    else
                    {
                        TextBox tb = (TextBox)table.Rows[i].Cells[j].FindControl("TextBoxRow_" + i + "Col_" + j);
                        tb.Text = Request.Form["TextBoxRow_" + i + "Col_" + j];
                    }
                }
            }
        }
    }

    private void GenerateTable(int rowsCount)
    {
        //Creat the Table and Add it to the Page
        Table table = new Table();
        table.ID = "Table1";
        Page.Form.Controls.Add(table);

        //The number of Columns to be generated
        const int colsCount = 3;//You can changed the value of 3 based on you requirements

        // Now iterate through the table and add your controls
        for (int i = 0; i < rowsCount; i++)
        {
            TableRow row = new TableRow();
            for (int j = 0; j < colsCount; j++)
            {
                TableCell cell = new TableCell();

                if (j == 0) //means the first column of the Table
                {
                    //Create the CheckBox
                    CheckBox cb = new CheckBox();
                    // Set a unique ID for each CheckBox
                    cb.ID = "CheckBoxRow_" + i + "Col_" + j;
                    // Add the control to the FIRST TableCell
                    cell.Controls.Add(cb);
                    // Add the TableCell to the TableRow
                    row.Cells.Add(cell);

                }
                else if (j == 1) //means the first column of the Table
                {
                    //Create the CheckBox
                    DropDownList ddl = new DropDownList();
                    // Set a unique ID for each CheckBox
                    ddl.ID = "DropDown_" + i + "Col_" + j;
                    ddl.EnableViewState = true;
                    ddl.EnableTheming = true;
                    ddl.AutoPostBack = true;
                    ddl.SelectedIndexChanged += new EventHandler(this.ddlArtikel_SelectedIndexChanged);
                    ddl.Items.Add("testttttttt");
                    ddl.Items.Add("testttttttt22");
                    ddl.Items.Add("testttttttt33");

                    // Add the control to the FIRST TableCell
                    cell.Controls.Add(ddl);
                    // Add the TableCell to the TableRow
                    row.Cells.Add(cell);

                }
                else
                {
                    //Create the TextBox
                    TextBox tb = new TextBox();
                    // Set a unique ID for each TextBox
                    tb.ID = "TextBoxRow_" + i + "Col_" + j;
                    // Add the control to the TableCell
                    cell.Controls.Add(tb);
                    // Add the TableCell to the TableRow
                    row.Cells.Add(cell);
                }
            }

            // And finally, add the TableRow to the Table
            table.Rows.Add(row);
        }

        //Set Previous Data on PostBacks
        SetPreviousData(rowsCount, colsCount);

        //Sore the current Rows Count in ViewState
        rowsCount++;
        ViewState["RowsCount"] = rowsCount;
    }

    private void GetSelectedRows()
    {
        if (ViewState["RowsCount"] != null)
        {
            numOfRows = Convert.ToInt32(ViewState["RowsCount"].ToString());
            int removedRows = numOfRows - 1;

            //Re create the Table on Postbacks
            GenerateTable(numOfRows - 1);

            Table table = (Table)Page.FindControl("Table1");
            if (table != null)
            {
                if (table.Rows.Count > 0)
                {
                    for (int i = table.Rows.Count - 1; i >= 0; i--)
                    {
                        //Get the Checked value of the CheckBox using the Request objects
                        string check = Request.Form["CheckBoxRow_" + i + "Col_" + 0];
                        //Extract the CheckBox Control from within the Table
                        if (check == "on") //If selected
                        {
                            table.Rows.Remove(table.Rows[i]);
                            removedRows--;
                        }
                    }
                    ViewState["RowsCount"] = removedRows + 1;
                }
            }
        }
    }


    protected void ddlArtikel_SelectedIndexChanged(object sender, EventArgs e)
    {
        try
        {

            numOfRows = Convert.ToInt32(ViewState["RowsCount"].ToString()) - 1;

            //Set Previous Data on PostBacks
            GenerateTable(numOfRows);

            Response.Write("Artikel Changed !!!");
        }
        catch (Exception ex)
        {
            Response.Write("Foutbericht Artikelchanged: " + ex.Message);
        }
    }



 }

}