473,554 Members | 2,414 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

C# multiple postback page with dynamic textboxes

2 New Member
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();

}

}
Mar 25 '08 #1
2 5011
Waazzzii
6 New Member
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
englishman69
2 New Member
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
2345
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 dropdown box, and a couple of textboxes just below it. When the user selects an option from the dropdown, it triggers a postback event, which...
5
2460
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 the page with a new selected from the header table, the textboxes is not loaded with the new details. During DEBUG, I could actually see the values...
10
4487
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 (basically have the data binding done in the If NOT IsPostBack Then statement). How come? How does this information get preserved? Which raises...
2
1685
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 textboxes and the dropdownlist) and lots more stuff on the page. When the user wants to save the page he'll click the save button. The server gets...
0
1023
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 a TableRow(TR) to an existing table using HtmlTableRow 2. I add TableCells(TD) to the above TR using HtmlTableCell 3. I add TextBoxes to the TDs...
2
4000
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 as indicated by microsoft. But I can't seem to save the number of controls in a viewstate variable or a session variable when creating them in...
2
4241
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. if i could explain: i have a list of reports in a datalist. a user clicks a report link. it goes off to reporting services, fetches the parameters...
4
4746
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 to demonstrate my issues. Lets say I have a WebForm with a DropDownList where the user selects a number from 1 to 10 (the DropDownList is not...
0
1499
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 an update panel. I store the ID for the generated textboxes in the Viewstate, which I use in the Panels' INIT eventhandler to go ahead and...
0
7612
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
1
7576
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7895
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6163
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5443
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5165
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
1
2027
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1147
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
853
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.