Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Dynamically adding controls to a panel

Status
Not open for further replies.

lupidus

MIS
Jun 1, 2003
30
US
Hello all,

My goal is to have a "New Row" button which allows the user to add new rows for input to a table. I have set the OnClick event for a button to call a c# function called NewRow. NewRow uses controls.add to add LiteralControl , DropDownList, and TextBoxes to the Panel.

The button works for the first click, but subsequent clicks don't add additional rows (and the newrow variable in my code isn't incremented). Do I need to be saving the ViewState of anything? I also attempted to use the OnTextChange call of a textbox instead of a button OnClick event to call my NewRow function, but the function never was called (a totally different problem , altogether, but odd nonetheless).

I came across a custom control ( that handles recreating dynamic controls on subsequent requests, but I wasn't able to get it working for Panels and I am still not sure if thats even the problem.

My code is below. Any help would be greatly appreciated. Thanks.

Code:
<%@ Page language="c#" Codebehind="contactadd.aspx.cs" AutoEventWireup="false" Src="contactadd.aspx.cs" Inherits="Contact.ContactAdd" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
	<HEAD>
		<title>Add Contact</title>
		<link rel="stylesheet" href="../NormalStyle.css">
	</head>
	<body>
	
	<form id="new_contact" method=post action="contactadd.asp?Action=Process" runat="server">
	<table id="top_table">
		<tr><td width=100>First Name: </td>
		<td width=100><asp:TextBox TextMode="SingleLine" Columns=35 Enabled=True Runat=server id="txtFName"></asp:TextBox></td></tr>
		
		<tr><td width=100>Last Name: </td>
		<td width=100><asp:TextBox TextMode="SingleLine" Columns=35 Enabled=True Runat=server id="txtLName"></asp:TextBox></td></tr>
			
		<tr><td width=100>Email: </td>
		<td width=100><asp:TextBox TextMode="SingleLine" Columns=35 Enabled=True Runat=server id="txtEmail"></asp:TextBox></td></tr>
			
		<tr><td width=100>Site/Group: </td><!--- datagrid displays possible locations -->
			<td><asp:dropDownList ID="ddSites" Runat="server"></asp:dropDownList></td>
		</tr>

		<tr><td width=100>Title/Job: </td><!--- datagrid displays possible jobs/titles-->
			<td><asp:dropDownList ID="ddJobs" Runat="server"></asp:dropDownList></td>
		</tr>
	</table>
	<table>
	<asp:Panel ID="panelMain" Runat="server">
		
			<tr class="tableheader">
				<td width=100><strong>Phone Type</strong></td>
				<td width=100><strong>Number</strong></td>
				<td width=100><strong>Extension</strong></td>
				<td width=100><strong>Contact Preference</strong></td>
				<td width=100><strong>Access Code</strong></td>
			</tr>
			<tr>
				<td width=100><asp:dropDownList id="ddPhoneType1" Runat="server"></asp:DropDownList></td>
				<td width=100><asp:TextBox TextMode="SingleLine"  Enabled=True Runat=server ID="txtNumber1" OnTextChanged=NewRow></asp:TextBox></td>
				<td width=100><asp:TextBox TextMode="SingleLine"  Enabled=True Runat=server ID="txtExt1"></asp:TextBox></td>		
				<td width=100><asp:TextBox TextMode="SingleLine"  Enabled=True Runat=server Columns=5 ID="txtPref1"></asp:TextBox></td>
				<td width=100><asp:TextBox TextMode="SingleLine" Enabled=True Runat=server Columns=5 ID="txtAccess1"></asp:TextBox></td>
			</tr>	
		
	</asp:Panel>
		</table>
		<table>
			<tr><td width=100>Comments:</td>
				<td><asp:TextBox ID="txtComments" Runat=server Height=50 Columns=50 TextMode=MultiLine></asp:TextBox></td>
			</tr>
		</table>
		
		
<asp:Button OnClick=NewRow ID="newrow" Enabled="True" Visible="True" Text="New Row" Runat="server" ></asp:Button>
<input type="submit" name="btnsubmit" value="Submit" id="btnsubmit"><input type="reset" name="btnreset" id="btnreset">
</form>

</body>
</html>

c#:
Code:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Threading;

namespace Contact
{

	public class ContactAdd : System.Web.UI.Page
	{

		
		protected System.Data.SqlClient.SqlConnection conn;
		protected System.Web.UI.WebControls.DropDownList ddSites;
		protected System.Web.UI.WebControls.DropDownList ddJobs;
		protected System.Web.UI.WebControls.TextBox txtFName;
		protected System.Web.UI.WebControls.TextBox txtLName;
		protected System.Web.UI.WebControls.TextBox txtEmail;

		protected System.Web.UI.WebControls.Panel panelMain; 
		protected System.Web.UI.WebControls.TextBox txtNumber1;
		protected System.Web.UI.WebControls.TextBox txtExt1;
		protected System.Web.UI.WebControls.TextBox txtAccess1;
		protected System.Web.UI.WebControls.TextBox txtPref1;
		protected System.Web.UI.WebControls.DropDownList ddPhoneType1;

		protected System.Web.UI.WebControls.Button button;

		int locationid, numrows=1;
		String city, state, country, connString, loc_string;

		public ContactAdd()
		{
			Page.Init += new System.EventHandler(Page_Init);
		}

		protected void PopulateSelect(String sqlCommand, String conn, String type )
		{
			SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand, connString);
			DataSet ds = new DataSet();
			if (type == "Locations") 
			{
				sqlDataAdapter.Fill (ds, "Locations");
				DataTable dataTable = ds.Tables[0];
				foreach (DataRow dataRow in dataTable.Rows) {	// populate dropdown for sites
					loc_string = dataRow["name"].ToString() + " - " + dataRow["city"].ToString() + ", " + dataRow["state"].ToString() + " " + dataRow["country"].ToString();
					ddSites.Items.Add(new ListItem(loc_string, dataRow["location_id"].ToString() ) ) ;
				}
			}
			else if (type == "Jobs") 
			{
				sqlDataAdapter.Fill(ds, "[Job Titles]");// fill the dataset	
				DataTable dataTable = ds.Tables[0];			// build datatable from the dataset
			
				foreach (DataRow dataRow in dataTable.Rows) {
					ddJobs.Items.Add(new ListItem(dataRow["job_title"].ToString() ) ) ;
				}

			}

			else if (type == "PhoneNumberTypes") 
			{
				sqlDataAdapter.Fill(ds, "[Contact Phones]");
				DataTable dataTable = ds.Tables[0];			
			
				foreach (DataRow dataRow in dataTable.Rows) 	{
					ddPhoneType1.Items.Add(new ListItem(dataRow["phone_type"].ToString() ) ) ;
				}		
			}
		}

		private void Page_Load(object sender, System.EventArgs e)
		{
			String type, sqlCommand;
			if (! IsPostBack ) 
			{
				Response.Write("postback = false" + "<BR>");
				connString = "...";

				sqlCommand="Select location_ID, name, city, state, country from locations order by city";
				type = "Locations";
				PopulateSelect(sqlCommand, connString, type);
				
				sqlCommand = "select * from [Job Titles] order by job_title";
				type = "Jobs";
				PopulateSelect(sqlCommand, connString, type);
				
				type = "PhoneNumberTypes";
				sqlCommand = "select distinct(phone_type) from [Contact Phones] where phone_type is not null";
				PopulateSelect(sqlCommand, connString, type);

				// save in ViewState (initialize) 
				ViewState ["numrows"] = numrows;

			} // end if !postback
			else { Response.Write("postback = true" + "<BR>"); 
				//numrows++;
					
			
			
			
			
			}
		} // end of PageLoad

		public void NewRow(object sender, EventArgs e)
		{
			
			numrows++;
			
			// read from ViewState
			//numrows = (int)ViewState["numrows"];

			Response.Write("NewRow called, numrows = " + numrows);
	
			panelMain.Controls.Add(new LiteralControl("<tr><td width=100>"));
			DropDownList ddl = new DropDownList();
			ddl.ID = "ddPhoneType" + numrows.ToString();	// append the row number to the end of the control ID
			// list phone number types
			connString = "...";
			string sqlCommand = "select distinct(phone_type) from [Contact Phones] where phone_type is not null";
			SqlDataAdapter sqlDataAdapterTypes = new SqlDataAdapter(sqlCommand, connString);
			DataSet dsTypes = new DataSet();
			sqlDataAdapterTypes.Fill ( dsTypes, "[Contact Phones]");
			DataTable dataTableTypes = dsTypes.Tables[0];
			foreach (DataRow dataRowTypes in dataTableTypes.Rows) {
				ddl.Items.Add(new ListItem(dataRowTypes["phone_type"].ToString() ) ) ;
			}

			panelMain.Controls.Add(ddl);		// add the dropdown list to the panel
			panelMain.Controls.Add(new LiteralControl("</td><td width=100>"));
		
			TextBox tbNumber = new TextBox();
			tbNumber.ID = "txtNumber" + numrows.ToString();
			
			panelMain.Controls.Add(tbNumber);
			panelMain.Controls.Add(new LiteralControl("</td><td width=100>"));

			TextBox tbExt = new TextBox();
			tbExt.ID = "txtExt" + numrows.ToString();

			panelMain.Controls.Add(tbExt);
			panelMain.Controls.Add(new LiteralControl("</td><td width=100>"));

			TextBox tbPref = new TextBox();
			tbPref.ID = "txtPref" + numrows.ToString();
			tbPref.Columns = 5;

			panelMain.Controls.Add(tbPref);
			panelMain.Controls.Add(new LiteralControl("</td><td width=100>"));

			TextBox tbAccess = new TextBox();
			tbAccess.ID = "txtAccess" + numrows.ToString();
			tbAccess.Columns = 5;
			
			panelMain.Controls.Add(tbAccess);
			panelMain.Controls.Add(new LiteralControl("</td></tr>"));
			// save in ViewState
			ViewState ["numrows"] = numrows;
		}

		private void Page_Init(object sender, EventArgs e)
		{
			InitializeComponent();
		}

		#region Web Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.Load += new System.EventHandler(this.Page_Load);

		}
		#endregion

	} // end of class definition
}	// end of namespace def
 
Is it possible to dynamically (as a result of an OnClick event) add controls to a panel, etc. without doing a postback? I assume there's no way around an asp:button doing a postback, but there doesn't seem to be a whole lot of other options:

Web controls with non-postback events: checkbox, checkboxlist, dropdownlist, listbox, radiobuttonlist, radiobutton and textbox.


 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top