C# multiple postback page with dynamic textboxes

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • englishman69
    New Member
    • Mar 2008
    • 2

    C# multiple postback page with dynamic textboxes

    Hello,
    I have been banging my head against this one for a while... Searches online have revealed many different proposals for correcting my issue but none that I can follow! My basic situation is this, I have a page which uses multiple postbacks to generate a list of dynamic text boxes with appropriate labels. However, when I do the final postback to enter the values in the dynamic textboxes into the database the values seem to become inaccessible. I have tried recreating the textboxes each time and linking them up with the ID attribute, but their values are never present. EnableViewState is set to true for all controls on the page.

    Here's the code-behind:

    public partial class Admin_DailyData Entry : System.Web.UI.P age
    {

    SqlConnection masterConnectio n = new SqlConnection(W ebConfiguration Manager.Connect ionStrings["Pubs"].ConnectionStri ng);

    protected void Page_Load(objec t sender, EventArgs e)
    {
    Button1.Visible = false;
    if (!Page.IsPostBa ck)
    {
    SqlCommand myCommand = new SqlCommand("SEL ECT * FROM brands ORDER BY brand_name", masterConnectio n);
    masterConnectio n.Open();
    SqlDataReader myReader = myCommand.Execu teReader();

    while (myReader.Read( ))
    {
    BrandDropDown.I tems.Add(new ListItem(myRead er["brand_name "].ToString(), myReader[0].ToString()));
    }
    masterConnectio n.Close();

    SqlCommand myCommand2 = new SqlCommand("SEL ECT * FROM hotel ORDER BY hotel_name", masterConnectio n);
    masterConnectio n.Open();
    SqlDataReader myReader2 = myCommand2.Exec uteReader();
    while (myReader2.Read ())
    {
    HotelDropDown.I tems.Add(new ListItem(myRead er2["hotel_name "].ToString(), myReader2[0].ToString()));
    }
    masterConnectio n.Close();

    // Build and hide input text boxes
    SqlCommand myCommand3 = new SqlCommand("SEL ECT * FROM accounts", masterConnectio n);
    masterConnectio n.Open();
    SqlDataReader myReader3 = myCommand3.Exec uteReader();
    while (myReader3.Read ())
    {
    TableRow rowNew = new TableRow();
    Table1.Controls .Add(rowNew);

    TableCell tc1 = new TableCell();
    TableCell tc2 = new TableCell();
    HtmlInputText inputText = new HtmlInputText() ;
    inputText.ID = myReader3["id"].ToString();
    tc1.Text = myReader3["account_de scr"].ToString() + " : ";
    tc2.Controls.Ad d(inputText);

    rowNew.Controls .Add(tc1);
    rowNew.Controls .Add(tc2);
    }
    masterConnectio n.Close();


    }
    }
    protected void HotelDropDown_S electedIndexCha nged(object sender, EventArgs e)
    {

    //connect to the database and pull down a list of the fields set up for the selected hotel ready to
    //create the data entry form programatically .
    Dictionary<stri ng, string> codeList = new Dictionary<stri ng, string>();
    {
    //Create array of account codes for later reference
    SqlCommand myCommand2 = new SqlCommand("SEL ECT * FROM accounts", masterConnectio n);
    masterConnectio n.Open();
    SqlDataReader myReader2 = myCommand2.Exec uteReader();
    while (myReader2.Read ())
    {
    codeList.Add(my Reader2[0].ToString(), myReader2[2].ToString());
    }
    masterConnectio n.Close();
    }

    SqlCommand myCommand = new SqlCommand("SEL ECT * FROM hotel_de_map WHERE hotel_id='" + HotelDropDown.S electedValue.To String() + "'", masterConnectio n);
    masterConnectio n.Open();
    SqlDataReader myReader = myCommand.Execu teReader();
    myReader.Read() ;
    Panel1.Controls .Add(new LiteralControl( "<table>")) ;

    for (int i = 0; i < myReader.FieldC ount; i++)
    {
    if (@myReader[i].ToString() == "1")
    {
    try
    {
    //create textbox and label for data entry purposes and house them in the Panel1 container
    TextBox dynTextbox = new TextBox();
    dynTextbox.ID = myReader.GetNam e(i);
    dynTextbox.Enab leViewState = true;
    dynTextbox.Text = "15"; //apply default values for testing only
    Label dynTextlabel = new Label();
    dynTextlabel.Te xt = codeList[myReader.GetNam e(i)] + ": ";
    Panel1.Controls .Add(new LiteralControl( "<tr><td align=left>"));
    Panel1.Controls .Add(dynTextlab el);
    Panel1.Controls .Add(new LiteralControl( "</td><td align=right>")) ;
    Panel1.Controls .Add(dynTextbox );
    Panel1.Controls .Add(new LiteralControl( "</td></tr>"));
    }
    catch (Exception ex)
    {
    System.Diagnost ics.Debug.Write Line(ex.ToStrin g());
    }
    }
    }
    Panel1.Controls .Add(new LiteralControl( "</table>"));
    Button1.Visible = true;
    masterConnectio n.Close();
    }

    protected void BrandDropDownLi st_SelectedInde xChanged(object sender, EventArgs e)
    {
    HotelDropDown.I tems.Clear();
    HotelDropDown.I tems.Add(new ListItem("Choos e Your Hotel...", "0"));
    SqlCommand myCommand3 = new SqlCommand("SEL ECT * FROM hotel WHERE brand_id LIKE '"+BrandDropDow n.SelectedValue .ToString()+"' ORDER BY hotel_name", masterConnectio n);
    masterConnectio n.Open();
    SqlDataReader myReader3 = myCommand3.Exec uteReader();

    while (myReader3.Read ())
    {
    HotelDropDown.I tems.Add(new ListItem(myRead er3[2].ToString(), myReader3[0].ToString()));
    }
    masterConnectio n.Close();

    }

    protected void Button1_Click(o bject sender, EventArgs e)
    {
    System.Diagnost ics.Debug.Write Line("========= =============== =============== ======");
    foreach (Control ctr in Panel1.Controls )
    {
    System.Diagnost ics.Debug.Write Line(ctr.GetTyp e().ToString()) ;
    }
    System.Diagnost ics.Debug.Write Line("========= =============== =============== ======");
    // Reestablish dynamic text boxes to allow for the reading of their data. This requires the building
    // of the dictionary collection too
    Dictionary<stri ng, string> codeList = new Dictionary<stri ng, string>();
    {
    //Create array of account codes for later reference
    SqlCommand myCommand2 = new SqlCommand("SEL ECT * FROM accounts", masterConnectio n);
    masterConnectio n.Open();
    SqlDataReader myReader2 = myCommand2.Exec uteReader();
    while (myReader2.Read ())
    {
    codeList.Add(my Reader2[0].ToString(), myReader2[2].ToString());
    }
    masterConnectio n.Close();
    }

    //dictionary collection for hotel capacity information
    Dictionary<stri ng, string> hotelData = new Dictionary<stri ng, string>();
    {
    //Create array of hotel capacities for later reference
    SqlCommand myCommandh = new SqlCommand("SEL ECT * FROM hotel", masterConnectio n);
    masterConnectio n.Open();
    SqlDataReader myReaderh = myCommandh.Exec uteReader();
    while (myReaderh.Read ())
    {
    hotelData.Add(m yReaderh["id"].ToString(), myReaderh["capacity"].ToString());
    }
    masterConnectio n.Close();

    }

    SqlCommand myCommand = new SqlCommand("SEL ECT * FROM hotel_de_map WHERE hotel_id='" + HotelDropDown.S electedValue.To String() + "'", masterConnectio n);
    masterConnectio n.Open();
    SqlDataReader myReader = myCommand.Execu teReader();
    myReader.Read() ;
    Panel1.Controls .Add(new LiteralControl( "<table>")) ;

    for (int i = 0; i < myReader.FieldC ount; i++)
    {
    if (@myReader[i].ToString() == "1")
    {
    try
    {
    //create textbox and label for data entry purposes and house them in the Panel1 container
    TextBox dynTextbox = new TextBox();
    dynTextbox.ID = myReader.GetNam e(i);
    dynTextbox.Enab leViewState = true;
    //dynTextbox.Text = "15";
    Label dynTextlabel = new Label();
    dynTextlabel.Te xt = codeList[myReader.GetNam e(i)] + ": ";
    Panel1.Controls .Add(new LiteralControl( "<tr><td align=left>"));
    Panel1.Controls .Add(dynTextlab el);
    Panel1.Controls .Add(new LiteralControl( "</td><td align=right>")) ;
    Panel1.Controls .Add(dynTextbox );
    Panel1.Controls .Add(new LiteralControl( "</td></tr>"));
    }
    catch (Exception ex)
    {
    System.Diagnost ics.Debug.Write Line(ex.ToStrin g());
    }
    }
    }
    Panel1.Controls .Add(new LiteralControl( "</table>"));
    Button1.Visible = true;
    masterConnectio n.Close();

    // With all dynamic text boxes rebuilt, they are available as part of the panel1.controls collection and can be read
    string queryForEntry = "";
    string queryColumns1 = "hotel_id,creat e_date,activity _date,username, ";
    string queryColumns2 = "hotel_id,entry _date,activity_ date,username,r ooms_avail,room s_rented,room_r ev_less_rewards ,room_allow_les s_rewards,";
    string queryData1 = HotelDropDown.S electedValue.To String() + ",'" + DateTime.Today + "','" + TextBox1.Text + "','" + User.Identity.N ame + "',";

    string queryData2 = queryData1 + hotelData[HotelDropDown.S electedValue.To String()] + ",";

    //read through the controls embedded in Panel1, if match to textbox, use id and value to build the query
    foreach (Control c in Panel1.Controls )
    {
    if (c.GetType().To String() == "System.Web.UI. WebControls.Tex tBox")
    {
    TextBox tempText = c as TextBox;

    queryColumns1 += "[" + tempText.ID + "],";
    queryData1 += "'" + tempText.Text + "',";
    if (Convert.ToInt3 2(tempText.ID) < 4)
    {
    queryData2 += "'" + tempText.Text + "',";
    }
    }
    }
    char[] charsToTrim = { ',' };
    queryColumns1 = queryColumns1.T rimEnd(charsToT rim);
    queryColumns2 = queryColumns2.T rimEnd(charsToT rim);
    queryData1 = queryData1.Trim End(charsToTrim );
    queryData2 = queryData2.Trim End(charsToTrim );
    queryForEntry = "INSERT INTO bulk_reporting_ data (" + queryColumns1 + ") VALUES (" + queryData1 + "); INSERT INTO main_data (" + queryColumns2 + ") VALUES (" + queryData2 + ")";
    System.Diagnost ics.Debug.Write Line(queryForEn try);

    //Query functions
    SqlCommand myCommand3 = new SqlCommand(quer yForEntry, masterConnectio n);
    masterConnectio n.Open();
    try
    {
    int myReader3 = myCommand3.Exec uteNonQuery();
    System.Diagnost ics.Debug.Write Line(myReader3. ToString() + " entries made");
    }
    catch (Exception e3)
    {
    System.Diagnost ics.Debug.Write Line(e3.ToStrin g());
    if (e3.ToString(). Contains("Canno t insert duplicate key row in object"))
    {
    Label1.Text = "<br><font color=red>Entry already exists </font><br>";
    }
    }
    masterConnectio n.Close();

    }

    }
  • Waazzzii
    New Member
    • Jan 2008
    • 6

    #2
    It looks like most of your tables and buttons are generated server side... Every time a page is posted back to, it acts as a 'refresh' in a way, so any value that was stored previously will be erased since the elements are re-populated.

    If you are using postbacks try using session state (or even better viewstate) to store the information. Possibly even create a list of the parameters you need, then store the list in a single viewstate object... remember anything in the viewstate will be erased once you leave the page- if you need to transfer pages then rather use Session variables to store your information.

    Comment

    • englishman69
      New Member
      • Mar 2008
      • 2

      #3
      Nevermind - solved the problem using sessions:

      Session["holdMe"] = Panel1;

      Thanks anyway!

      Comment

      Working...