473,405 Members | 2,261 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,405 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 4997
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

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

Similar topics

1
by: Christopher D. Wiederspan | last post by:
I'm wondering if there's a way to use javascript to disable a ASP.NET web page before it starts to postback. Specifically, here's what I'm running into. I've got a webform that has an autopostback...
5
by: John Cosmas | last post by:
I have a form that has a listbox on the top that is bound to a header table. When the page first loads, it paints the adjacent textboxes with data from the details table. However, when I postback...
10
by: Krista Lemieux | last post by:
I'm new to ASP.NET and I'm not use to the way things are handled with this technology. I've been told that when I have a control, I should only bind the data to it once, and not on each post back...
2
by: Pipo | last post by:
Nobody knows how to get the values provided in the client can be read in the user-control? If have made a Web Custom Control with 2 textboxes and 1 dropdownlist. The user fills in my control (the...
0
by: Merdaad | last post by:
Hi, I am using ASP.NET 2.0 with C#. On a page I have a few (static) textboxes that get populated from database and then I create other textboxes during runtime using the folloiwng steps: 1. I add...
2
by: paulcis | last post by:
I am trying to produce a dynamic form from a database with unknown amount of records. I need to read the values and create a new textbox for each. I need to create the textboxes at page_init stage...
2
by: =?Utf-8?B?TG91aXNhOTk=?= | last post by:
Hello. ive just read some posts on the age old issue of losing dynamic control values on postback. Most people say recreate the controls on the onInit, but i just dont think this serves my purpose....
4
by: =?Utf-8?B?RHlsYW5TbWl0aA==?= | last post by:
I have a WebForm where I'm dynamically creating some controls and I'm having difficulty understanding how the state is being persisted and how to work with it. I've created a simplified example...
0
by: rvdnieuwenhuizen | last post by:
Hi, The problem I cannot seem to solve: I have a page with a button control. In the On_Click eventhandler I dynamically add one TextBox each time the button is clicked. I add the textboxes to...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

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.