472,126 Members | 1,448 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,126 software developers and data experts.

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_DailyDataEntry : System.Web.UI.Page
{

SqlConnection masterConnection = new SqlConnection(WebConfigurationManager.ConnectionSt rings["Pubs"].ConnectionString);

protected void Page_Load(object sender, EventArgs e)
{
Button1.Visible = false;
if (!Page.IsPostBack)
{
SqlCommand myCommand = new SqlCommand("SELECT * FROM brands ORDER BY brand_name", masterConnection);
masterConnection.Open();
SqlDataReader myReader = myCommand.ExecuteReader();

while (myReader.Read())
{
BrandDropDown.Items.Add(new ListItem(myReader["brand_name"].ToString(), myReader[0].ToString()));
}
masterConnection.Close();

SqlCommand myCommand2 = new SqlCommand("SELECT * FROM hotel ORDER BY hotel_name", masterConnection);
masterConnection.Open();
SqlDataReader myReader2 = myCommand2.ExecuteReader();
while (myReader2.Read())
{
HotelDropDown.Items.Add(new ListItem(myReader2["hotel_name"].ToString(), myReader2[0].ToString()));
}
masterConnection.Close();

// Build and hide input text boxes
SqlCommand myCommand3 = new SqlCommand("SELECT * FROM accounts", masterConnection);
masterConnection.Open();
SqlDataReader myReader3 = myCommand3.ExecuteReader();
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_descr"].ToString() + " : ";
tc2.Controls.Add(inputText);

rowNew.Controls.Add(tc1);
rowNew.Controls.Add(tc2);
}
masterConnection.Close();


}
}
protected void HotelDropDown_SelectedIndexChanged(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<string, string> codeList = new Dictionary<string, string>();
{
//Create array of account codes for later reference
SqlCommand myCommand2 = new SqlCommand("SELECT * FROM accounts", masterConnection);
masterConnection.Open();
SqlDataReader myReader2 = myCommand2.ExecuteReader();
while (myReader2.Read())
{
codeList.Add(myReader2[0].ToString(), myReader2[2].ToString());
}
masterConnection.Close();
}

SqlCommand myCommand = new SqlCommand("SELECT * FROM hotel_de_map WHERE hotel_id='" + HotelDropDown.SelectedValue.ToString() + "'", masterConnection);
masterConnection.Open();
SqlDataReader myReader = myCommand.ExecuteReader();
myReader.Read();
Panel1.Controls.Add(new LiteralControl("<table>"));

for (int i = 0; i < myReader.FieldCount; 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.GetName(i);
dynTextbox.EnableViewState = true;
dynTextbox.Text = "15"; //apply default values for testing only
Label dynTextlabel = new Label();
dynTextlabel.Text = codeList[myReader.GetName(i)] + ": ";
Panel1.Controls.Add(new LiteralControl("<tr><td align=left>"));
Panel1.Controls.Add(dynTextlabel);
Panel1.Controls.Add(new LiteralControl("</td><td align=right>"));
Panel1.Controls.Add(dynTextbox);
Panel1.Controls.Add(new LiteralControl("</td></tr>"));
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.ToString());
}
}
}
Panel1.Controls.Add(new LiteralControl("</table>"));
Button1.Visible = true;
masterConnection.Close();
}

protected void BrandDropDownList_SelectedIndexChanged(object sender, EventArgs e)
{
HotelDropDown.Items.Clear();
HotelDropDown.Items.Add(new ListItem("Choose Your Hotel...", "0"));
SqlCommand myCommand3 = new SqlCommand("SELECT * FROM hotel WHERE brand_id LIKE '"+BrandDropDown.SelectedValue.ToString()+"' ORDER BY hotel_name", masterConnection);
masterConnection.Open();
SqlDataReader myReader3 = myCommand3.ExecuteReader();

while (myReader3.Read())
{
HotelDropDown.Items.Add(new ListItem(myReader3[2].ToString(), myReader3[0].ToString()));
}
masterConnection.Close();

}

protected void Button1_Click(object sender, EventArgs e)
{
System.Diagnostics.Debug.WriteLine("============== ===============================");
foreach (Control ctr in Panel1.Controls)
{
System.Diagnostics.Debug.WriteLine(ctr.GetType().T oString());
}
System.Diagnostics.Debug.WriteLine("============== ===============================");
// Reestablish dynamic text boxes to allow for the reading of their data. This requires the building
// of the dictionary collection too
Dictionary<string, string> codeList = new Dictionary<string, string>();
{
//Create array of account codes for later reference
SqlCommand myCommand2 = new SqlCommand("SELECT * FROM accounts", masterConnection);
masterConnection.Open();
SqlDataReader myReader2 = myCommand2.ExecuteReader();
while (myReader2.Read())
{
codeList.Add(myReader2[0].ToString(), myReader2[2].ToString());
}
masterConnection.Close();
}

//dictionary collection for hotel capacity information
Dictionary<string, string> hotelData = new Dictionary<string, string>();
{
//Create array of hotel capacities for later reference
SqlCommand myCommandh = new SqlCommand("SELECT * FROM hotel", masterConnection);
masterConnection.Open();
SqlDataReader myReaderh = myCommandh.ExecuteReader();
while (myReaderh.Read())
{
hotelData.Add(myReaderh["id"].ToString(), myReaderh["capacity"].ToString());
}
masterConnection.Close();

}

SqlCommand myCommand = new SqlCommand("SELECT * FROM hotel_de_map WHERE hotel_id='" + HotelDropDown.SelectedValue.ToString() + "'", masterConnection);
masterConnection.Open();
SqlDataReader myReader = myCommand.ExecuteReader();
myReader.Read();
Panel1.Controls.Add(new LiteralControl("<table>"));

for (int i = 0; i < myReader.FieldCount; 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.GetName(i);
dynTextbox.EnableViewState = true;
//dynTextbox.Text = "15";
Label dynTextlabel = new Label();
dynTextlabel.Text = codeList[myReader.GetName(i)] + ": ";
Panel1.Controls.Add(new LiteralControl("<tr><td align=left>"));
Panel1.Controls.Add(dynTextlabel);
Panel1.Controls.Add(new LiteralControl("</td><td align=right>"));
Panel1.Controls.Add(dynTextbox);
Panel1.Controls.Add(new LiteralControl("</td></tr>"));
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.ToString());
}
}
}
Panel1.Controls.Add(new LiteralControl("</table>"));
Button1.Visible = true;
masterConnection.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,create_date,activity_date,username," ;
string queryColumns2 = "hotel_id,entry_date,activity_date,username,rooms_ avail,rooms_rented,room_rev_less_rewards,room_allo w_less_rewards,";
string queryData1 = HotelDropDown.SelectedValue.ToString() + ",'" + DateTime.Today + "','" + TextBox1.Text + "','" + User.Identity.Name + "',";

string queryData2 = queryData1 + hotelData[HotelDropDown.SelectedValue.ToString()] + ",";

//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().ToString() == "System.Web.UI.WebControls.TextBox")
{
TextBox tempText = c as TextBox;

queryColumns1 += "[" + tempText.ID + "],";
queryData1 += "'" + tempText.Text + "',";
if (Convert.ToInt32(tempText.ID) < 4)
{
queryData2 += "'" + tempText.Text + "',";
}
}
}
char[] charsToTrim = { ',' };
queryColumns1 = queryColumns1.TrimEnd(charsToTrim);
queryColumns2 = queryColumns2.TrimEnd(charsToTrim);
queryData1 = queryData1.TrimEnd(charsToTrim);
queryData2 = queryData2.TrimEnd(charsToTrim);
queryForEntry = "INSERT INTO bulk_reporting_data (" + queryColumns1 + ") VALUES (" + queryData1 + "); INSERT INTO main_data (" + queryColumns2 + ") VALUES (" + queryData2 + ")";
System.Diagnostics.Debug.WriteLine(queryForEntry);

//Query functions
SqlCommand myCommand3 = new SqlCommand(queryForEntry, masterConnection);
masterConnection.Open();
try
{
int myReader3 = myCommand3.ExecuteNonQuery();
System.Diagnostics.Debug.WriteLine(myReader3.ToStr ing() + " entries made");
}
catch (Exception e3)
{
System.Diagnostics.Debug.WriteLine(e3.ToString());
if (e3.ToString().Contains("Cannot insert duplicate key row in object"))
{
Label1.Text = "<br><font color=red>Entry already exists </font><br>";
}
}
masterConnection.Close();

}

}
Mar 25 '08 #1
2 4852
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.
Mar 25 '08 #2
Nevermind - solved the problem using sessions:

Session["holdMe"] = Panel1;

Thanks anyway!
Mar 25 '08 #3

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

1 post views Thread by Christopher D. Wiederspan | last post: by
5 posts views Thread by John Cosmas | last post: by
10 posts views Thread by Krista Lemieux | last post: by
2 posts views Thread by =?Utf-8?B?TG91aXNhOTk=?= | last post: by
4 posts views Thread by =?Utf-8?B?RHlsYW5TbWl0aA==?= | last post: by
reply views Thread by rvdnieuwenhuizen | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.