Rendering server control in a callback - c#

I have a bunch of different panels that are custom server controls, which inherits CompositeControl. The panels are rendered by using the CreateChildControls(). I have a page where I am displaying them based off of a users selection from a comboBox. When you change the selection it does a callback for a callback panel (DevExpress control), which is like an update panel. Based on the selection it adds the panel to the callback panel. But it seems that if you do this from a callback the server controls life cycle doesn't get started, so it never calls CreateChildControls() or OnPreRender(). Any ideas on how to make this work? EnsureChildControls() doesn't seem to helping.
Here is some example code of one of the panels
protected override void CreateChildControls()
{
base.CreateChildControls();
String strParentID = this.ClientInstanceName.Length > 0 ? this.ClientInstanceName : this.ClientID;
String strID = "";//Used as ID and ClientInstanceName.
String strKey = "";//Used in the ID and as the ControlInfo key.
if (!DesignMode)
{
//*******************************************************************
ASPxLabel lblUnit = new ASPxLabel();
lblUnit.Text = "Select Unit(s)";
callbackEdit.Controls.Add(lblUnit);
//*******************************************************************
strKey = "btnUnitSelector";
strID = strParentID + "_" + strKey;
btnUnitSelector = new ASPxButton()
{
ID = strID,
ClientInstanceName = strID,
CssFilePath = this.CssFilePath,
CssPostfix = this.CssPostfix,
SpriteCssFilePath = this.SpriteCssFilePath,
};
btnUnitSelector.Width = Unit.Pixel(180);
btnUnitSelector.AutoPostBack = false;
this.listControlInfo.Add(new ControlInfo(strKey, btnUnitSelector.ClientInstanceName, btnUnitSelector.ClientID));
callbackEdit.Controls.Add(btnUnitSelector);
//*******************************************************************
strKey = "unitPopup";
strID = strParentID + "_" + strKey;
unitPopup = new UnitPopup.UnitPopup();
unitPopup.ID = strID;
unitPopup.ClientInstanceName = strID;
unitPopup.btnOk_AutoPostBack = false;
unitPopup.ShowOnlyUnits = false;
unitPopup.DataSource = GlobalProperties.Company_UnitsAndAreas;
unitPopup.DataBind();
btnUnitSelector.ClientSideEvents.Click = "function (s, e) { " + unitPopup.ClientInstanceName + ".Show(); }";
unitPopup.ClientSideEvents.MemberSet = "function (s, e) { " + btnUnitSelector.ClientInstanceName + ".SetText(" + unitPopup.ClientInstanceName + ".selectedMemberName); }";
Controls.Add(unitPopup);
//*******************************************************************
}
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
ClientScriptManager cs = this.Page.ClientScript;
//Register an embedded JavaScript file. The JavaScript file needs to have a build action of "Embedded Resource".
String resourceName = "QSR_ServerControls.Controls.DashboardControls.SalesChart.SalesChart.js";
cs.RegisterClientScriptResource(typeof(SalesChart), resourceName);
}
Here is some sample code of adding a panel
private void PopulatePanel(string panel)
{
tblDescCell.Controls.Add(new LiteralControl(GetPanels().Select("[PanelName] = '" + panel + "'")[0]["PanelDescription"].ToString()));
if (panel == "SalesChart")
tblTopLeftCell.Controls.Add(new SalesChart.SalesChart());
}
void callbackMain_Callback(object sender, DevExpress.Web.ASPxClasses.CallbackEventArgsBase e)
{
PopulatePanel(e.Parameter);
}

During callback requests PreRender and Render methods are not executed (this is the main difference from PostBack request). But CreateChildControls should be executed. Please provide more information or code example.

Related

read the texts of run-time added textboxes

I have an application where the user can add any number of tabpages depending on what he/she needs. These tabpages have identical controls (textboxes and labels).
The controls on each tabpages are named like this: (on tabpage1 the controls are named: txtServer1, txtPort1, txtUser1, txtDbName1. if the user clicks the 'add another connection button' the application creates a second tabpage and the controls will be named: txtServer2, txtPort2, txtUser2, txtDbName2) and so on...
for example if the user have multiple tabpages to set-up:
the user clicks the 'add another connection' and the another tabpage with identical controls has been created and the user fills it up with appropriate data:
same thing goes here:
here's the code for dynamically added tabpage with controls:
//when 'add another connection' button is clicked
private void btnAddConnection_Click(object sender, EventArgs e)
{
string tabTitle = "Connection " + (tabControl1.TabCount + 1).ToString();
TabPage tabPage = new TabPage(tabTitle);
tabControl1.TabPages.Add(tabPage);
}
//when another tabpage has been added to tabcontrol
private void tabControl1_ControlAdded(object sender, ControlEventArgs e)
{
//control instances
TextBox txtServer = new TextBox();
TextBox txtPort = new TextBox();
TextBox txtUser = new TextBox();
TextBox txtDbName = new TextBox();
Label lblServer = new Label();
Label lblPort = new Label();
Label lblUser = new Label();
Label lblDbName = new Label();
tabControl1.SelectedTab = tabControl1.TabPages[tabControl1.TabCount - 1]; //select the newly addded tabpage
tabControl1.SelectedTab.BackColor = tabPage1.BackColor; //tabpage background color
//lblServer Properties
lblServer.Location = lblServer1.Location;
lblServer.Text = lblServer1.Text;
lblServer.ForeColor = lblServer1.ForeColor;
lblServer.Name = "lblServer" + tabControl1.TabCount.ToString();
//lblPort Properties
lblPort.Location = lblPort1.Location;
lblPort.Text = lblPort1.Text;
lblPort.ForeColor = lblPort1.ForeColor;
lblPort.Name = "lblPort" + tabControl1.TabCount.ToString();
//lblUser Properties
lblUser.Location = lblUser1.Location;
lblUser.Text = lblUser1.Text;
lblUser.ForeColor = lblUser1.ForeColor;
lblUser.Name = "lblUser" + tabControl1.TabCount.ToString();
//lblDbName Properties
lblDbName.Location = lblDbName1.Location;
lblDbName.Text = lblDbName1.Text;
lblDbName.ForeColor = lblDbName1.ForeColor;
lblDbName.Name = "lblDbName" + tabControl1.TabCount.ToString();
//txtserver properties
txtServer.Location = txtServer1.Location;
txtServer.Width = txtServer1.Width;
txtServer.Height = txtServer1.Height;
txtServer.Font = txtServer1.Font;
txtServer.Name = "txtServer" + tabControl1.TabCount.ToString();
//txtport properties
txtPort.Location = txtPort1.Location;
txtPort.Width = txtPort1.Width;
txtPort.Height = txtPort1.Height;
txtPort.Font = txtPort1.Font;
txtPort.Name = "txtPort" + tabControl1.TabCount.ToString();
//txtuser properties
txtUser.Location = txtUser1.Location;
txtUser.Width = txtUser1.Width;
txtUser.Height = txtUser1.Height;
txtUser.Font = txtUser1.Font;
txtUser.Name = "txtUser" + tabControl1.TabCount.ToString();
//txtdbname properties
txtDbName.Location = txtDbName1.Location;
txtDbName.Width = txtDbName1.Width;
txtDbName.Height = txtDbName1.Height;
txtDbName.Font = txtDbName1.Font;
txtDbName.Name = "txtUser" + tabControl1.TabCount.ToString();
//add controls to tabpage
tabControl1.SelectedTab.Controls.Add(lblServer);
tabControl1.SelectedTab.Controls.Add(lblPort);
tabControl1.SelectedTab.Controls.Add(lblUser);
tabControl1.SelectedTab.Controls.Add(lblDbName);
tabControl1.SelectedTab.Controls.Add(txtServer);
tabControl1.SelectedTab.Controls.Add(txtPort);
tabControl1.SelectedTab.Controls.Add(txtUser);
tabControl1.SelectedTab.Controls.Add(txtDbName);
}
When the user clicks the save button, I want the application to read each text in the textboxes (except for that url text) so that I can save it to a configuration file.
all I can think of is this
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
string connection;
for (int i = 1; i <= tabControl1.TabCount; i++ )
{
connection = "server=" + txtServer[i].Text + ";port=" txtPort[i].Text + ";user=" + txtUser[i].Text + ";dbname=" + txtDbName[i];
//save to config file code goes here...
}
}
and I know this is not correct.
any solution for this? thanks :)
This is the simplest way you can try this just use below function to get text from control in tabpage
public string getValue(string controlName, TabPage selectedTab)
{
if (selectedTab.Controls.ContainsKey(controlName)){
TextBox selectedtb = (TextBox)selectedTab.Controls[controlName];
return selectedtb.Text;
}
else
return null;
}
and in your save code use it like below
string connection;
int i = 1;
TabControl.TabPageCollection pages = tabControl1.TabPages;
foreach (TabPage page in pages)
{
connection = "server=" + getValue("txtServer"+i,page) + ";port=" +getValue("txtPort"+i,page) + ";user=" + getValue("txtUser"+i,page) + ";dbname=" + getValue("txtDbName"+i,page);
i++;
//save to config file code goes here...
}
txtServer[i].Text it's true but You have not defined an array.
You can do it like this
//global
List<TextBox> txtServerList= new List<TextBox>();
private void tabControl1_ControlAdded(object sender, ControlEventArgs e)
{
txtServer.Location = txtServer1.Location;
txtServer.Width = txtServer1.Width;
txtServer.Height = txtServer1.Height;
txtServer.Font = txtServer.Font;
txtServer.Name = "txtServer" + tabControl1.TabCount.ToString();
txtServerList.Add(txtServer)
.
.
.
}
Finally
for (int i = 1; i <= tabControl1.TabCount; i++ )
{
connection=txtServerList.get(i).Text + ......
}
You could just loop over the controls and find the matching name, something like this:
foreach(var page in tabControl1.TabPages){
var server = ProcessControls(page.Controls, "txtServer");
//... continue with the others
}
private TextBox ProcessControls(Control ctrlContainer, string name)
{
foreach (Control ctrl in ctrlContainer.Controls)
{
if (ctrl.GetType() == typeof(TextBox))
{
if(ctrl.Name.StartsWith(name))
return (TextBox)ctrl;
}
}
}
You can use an ArrayList to store and access all dynamically added controls. Set a name for each dynamically added controls. It can be based on the size of ArrayList.
I will not show the exact systax of c#.
first
declare an ArrayList or List(Type Safe)
List<Button> buttons = new List<Button>();
We just created a storage for our buttons that will be added at runtime.
void your_event (some parameters) {
Button temp = new Button("Hello");
temp.Name="button_name";
YourMainPanel.Controls.add(temp);
//after creating your button add it to the parent container. of any control where you want this button to be added.
//you can also set the coordinates of the button if you like
//after creating the button we need to add it to our List so that we can
//access it later, since the value of the 'temp' will change after this
//event was invoked in the future.
buttons.add(temp);
}
There are several ways to get the items in List<T>. One is by using index.
void someMethod(some parameters) {
Button button = buttons.ElementAt(index);
}

Passing variables to another Webpage

I'm trying to get variables from textboxes in one page, then pass them to be displayed in another page. Seems like I should use sessions (since that was the topic this assignment is for). The commented-out code is various methods I've tried that have not worked.
On the start page:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
UnobtrusiveValidationMode = System.Web.UI.UnobtrusiveValidationMode.None;
}
//This is a button link that sends to the next page, "Results"
protected void cbtnlSubmit_Click(object sender, EventArgs e)
{
string sName = "";
int sSize = 0;
string sTopping = "";
decimal sPrice = 0M;
if (IsPostBack)
{
Validate();
if (IsValid)
{
sName = ctbName.Text;
sSize = Convert.ToInt32(ctbSize.Text);
sTopping = ctbTopping.Text;
sPrice = Convert.ToDecimal(ctbPrice.Text);
if (string.IsNullOrEmpty(sTopping) == true)
{
sTopping = "cheese";
}
/* DOESN'T WORK
Session.Add(sName, sSize);
Session.Add(sTopping, sPrice);
Server.Transfer("Results.aspx");
*/
/*DOESN'T WORK
Session["pizza"] = new Pizza()
{
name = sName,
size = sSize,
topping = sTopping,
price = sPrice
};
*/
//ALSO DOESN'T WORK
Session["name"] = sName;
Session["size"] = sSize;
Session["topping"] = sTopping;
Session["price"] = sPrice;
Response.Redirect("Results.aspx");
}
}
}
}
This is the "Results" page that should display the variables
public partial class Results : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Session.Count != 0)
{
lblName.Text = Session["name"].ToString();
string size = Session["size"].ToString();
string topping = Session["topping"].ToString();
string price = Session["price"].ToString();
string pizzaInfo = (size + " inch pizza with " + topping + " for $" + price.ToString());
lblPizzaInfo.Text = pizzaInfo;
/*
string name = Session.Keys[0];
int size = Convert.ToInt32(Session[name]);
string topping = Session.Keys[1];
decimal price = Convert.ToDecimal(Session[topping]);
string pizzaInfo = (size.ToString() + " inch pizza with " + topping + " for $" + price.ToString());
lblName.Text = name;
lblPizzaInfo.Text = pizzaInfo;
*/
}
lblName.Text = "Meaghan";
}
}
Both pages display. The lblName.Text set at the end of the secondary page is a test to make sure the labels are visible (they are), but no information is being passed to the secondary page. That label only displays if I put it outside the if statement; nothing inside the if statement executes. I have tried reading the recommended questions and discovered I should enable "sessionState", which I did for both pages, but the program still doesn't work.
I selected EnableSessionState as True in the properties and it says EnableSessionState = "True" at the top of the aspx files. I added to the web.config file. So I guess the session state mode is "InProc" mode?
I tried adding the Session["test"] = "Hello" into the Default page and Response.Write(Session["test"]) into the Results page. Now it throws a NullReferenceException at lblName.Text = Session["name"].ToString() [inside the if statement].
You need the following in your Web.config at the root of your project:
<sessionState mode="InProc" cookieless="false" timeout="10" />
Can you please confirm or not if you have this entry in your config file ?
It should be located under
<configuratio>
<system.Web>
Further information on sessionState: https://msdn.microsoft.com/en-us/library/h6bb9cz9(v=vs.71).aspx

Problems with textboxes and page load in C#

Okay here I have some code from my project at the moment.
Basically the user goes onto the page and their current password is in the password textbox, and their avatar is selected in the droplist.
They can change their password by editing the text in the textbox and change their avatar by selecting a new one from the list. This is then written to the file where this information is kept. It writes to the file okay, but it writes what was initially in the textbox and droplist.
If i comment out these lines in the page load:
avatarDropList.SelectedValue = Session["avatar"].ToString();
newPasswordTextbox.Text = Session["password"].ToString();
It updates the file properly, but this is not what I want as I want the old password displayed there initially as well as the avatar to be selected in the dropbox.
Code below:
public partial class TuitterProfile : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
avatarImage.ImageUrl = "~/images/avatars/" + Session["avatar"] + ".gif";
avatarDropList.SelectedValue = Session["avatar"].ToString();
userNameTextbox.Text = Session["user"].ToString();
newPasswordTextbox.Text = Session["password"].ToString();
}
protected void okButton_Click(object sender, ImageClickEventArgs e)
{
string username = Session["user"].ToString();
string password = Session["password"].ToString();
string newPassword = newPasswordTextbox.Text;
string newAvatar = avatarDropList.SelectedValue;
int allDataReference = -1;
//Each element in the array is a string(Username Password Avatar)
string[] allData = File.ReadAllLines(Server.MapPath("~") + "/App_Data/tuitterUsers.txt");
for (int i = 0; i < allData.Length; i++)
{
string[] user = allData[i].Split(' ');
if (user[0] == username && user[1] == password)
{
allDataReference = i;
}
}
if (allDataReference > -1)
{
Session["avatar"] = newAvatar;
Session["password"] = newPassword;
allData[allDataReference] = username + " " + newPassword + " " + newAvatar;
File.WriteAllLines(Server.MapPath("~") + "/App_Data/tuitterUsers3.txt", allData);
}
}
}
In the ASP.Net page event lifecycle, Page_Load is called on every request. What you are doing here is resetting the value of the TextBox every time the page loads, which will include the time that you press the button to save the profile.
All you need to do is check for the current request being a postback when you set your initial values:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
avatarImage.ImageUrl = "~/images/avatars/" + Session["avatar"] + ".gif";
avatarDropList.SelectedValue = Session["avatar"].ToString();
userNameTextbox.Text = Session["user"].ToString();
newPasswordTextbox.Text = Session["password"].ToString();
}
}

Gridview Edit/Update is not working?

Here i am updating the gridview value but the value is not updating..TextBox txtID,TextBox txtName,TextBox txtAge retains the older value only and the value is not getting updated..Can anyone tel me like what am i doing wrong here
Here is my code
protected void gvTemp_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
CreateDataSkeletton(Convert.ToInt16(Session["intTabIndex"]));
GridViewRow row = (GridViewRow)gvTemp.Rows[e.RowIndex];
int autoid = Int32.Parse(gvTemp.DataKeys[e.RowIndex].Value.ToString());
int id = Convert.ToInt32(gvTemp.DataKeys[e.RowIndex].Values[0].ToString());
activeTabIndex = Convert.ToInt16(Session["activeTabIndex"]);
TextBox txtID = ((TextBox)gvTemp.Rows[e.RowIndex].FindControl("txtId"));
TextBox txtName = (TextBox)gvTemp.Rows[e.RowIndex].FindControl("txtName");
TextBox txtAge = (TextBox)gvTemp.Rows[e.RowIndex].FindControl("txtAge");
dataSetInSession.Tables["Days" + activeTabIndex.ToString()].Rows[e.RowIndex]["ID"] = txtID.Text;
dataSetInSession.Tables["Days" + activeTabIndex.ToString()].Rows[e.RowIndex]["Name"] = txtName.Text;
dataSetInSession.Tables["Days" + activeTabIndex.ToString()].Rows[e.RowIndex]["Age"] = txtAge.Text;
gvTemp.DataSource = dataSetInSession.Tables["Days" + activeTabIndex.ToString()];
gvTemp.DataBind();
gvTemp.EditIndex = -1;
}
and
private void CreateDataSkeletton(int intTabIndex)
{
dataSetInSession = new DataSet();
Session["intTabIndex"] = intTabIndex;
if (Session["dataSetInSession"] != null)
{
dataSetInSession = (DataSet)Session["dataSetInSession"];
}
if (dataSetInSession.Tables["Days" + intTabIndex].Rows.Count > 0)
{
gvTemp.DataSource = dataSetInSession.Tables["Days" + intTabIndex];
gvTemp.DataBind();
}
else
{
gvTemp.DataSource = dataSetInSession.Tables["Days"];
gvTemp.DataBind();
}
temp.Controls.Add(gvTemp);
}
Any suggestion??
EDIT(1):
protected void Page_Init(object sender, EventArgs e)
{
if (!IsPostBack)
{
AddDataTable();
}
dataSetInSession = new DataSet();
if (Session["dataSetInSession"] != null)
{
dataSetInSession = (DataSet)Session["dataSetInSession"];
}
if (Session["dynamicTabIDs"] != null)
{
//if dynamicTabIDs are in session, recreating the Tabs
//that are associated with the Tab IDs
//and adding them to the TabContainer that will contain
//all of the dynamic tabs.
//retrieving the tab IDs from session:
dynamicTabIDs = (List<string>)Session["dynamicTabIDs"];
if (TabContainerContent.ActiveTabIndex == -1)
{
TabContainerContent.ActiveTabIndex = Convert.ToInt16(Session["intTabIndex"]);
}
CreateDataSkeletton(Convert.ToInt16(Session["intTabIndex"]));
//looping through each TabID in session
//and recreating the TabPanel that is associated with that tabID
foreach (string tabID in dynamicTabIDs)
{
//creating a new TabPanel that is associated with the TabID
AjaxControlToolkit.TabPanel tab = new AjaxControlToolkit.TabPanel();
//TabContainerContent.ActiveTabIndex = tab;
//Setting the ID property of the TabPanel
tab.ID = tabID;
//setting the TabPanel's HeaderText
tab.HeaderText = "Days " + (TabContainerContent.Tabs.Count + 1).ToString();
//creating a Label to add to the TabPanel...at this point you'll have to
//create whatever controls are required for the tab...
Label tabContent = new Label();
//Giving the Label an ID
tabContent.ID = "lbl_tab_" + TabContainerContent.Tabs.Count.ToString();
//Setting the Label's text
tabContent.Text = "Tab " + (TabContainerContent.Tabs.Count + 1).ToString();
//Adding the Label to the TabPanel
tab.Controls.Add(tabContent);
//Adding the TabPanel to the TabContainer that contains the dynamic tabs
TabContainerContent.Tabs.Add(tab);
}
}
else
{ //Creating a new list of dynamicTabIDs because one doesn't exist yet in session.
dynamicTabIDs = new List<string>();
}
}
protected void Page_Load(object sender, EventArgs e)
{
}
Read Page Life Cycle
And you will get, that if you want to bind in code-behind, you should do it in Init Event, other wise there are no events will fire.
It seems to be Page.IsPostback problem.Need to add Page.IsPostback property in your page_load like
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
// Put your code inside that.
}
}
Actually your control is getting new value but when you click for updation then it calls old value from page_load.So try to put Page.IsPostback into your page_load event,Just like i mentioned.
I hope it helps.

Getting checkbox tags (in a panel) to new form

Rather new to C# so please forgive me if i am missing something simple or am trying to just do this the wrong way.
I am creating another form to compliment my main form and it needs to pull some of the information from Main form on button click of Second form. The information on the Main for is stored in checkboxes and textboxes.
I have the textboxes working fine but cannot figure out how to pull the checkboxes tag data over along with the formatting. Main Form is working fine as is except I cannot figure out how to bring the checkbox data over as well.
This is the code i currently use to display the checkbox TAG data on my main form.
//Statements to write checkboxes to stringbuilder
string checkBoxesLine = "\u2022 LIGHTS ";
foreach (Control control in pnlCheckBoxes.Controls)
{
if (control is CheckBox)
{
CheckBox checkBox = (CheckBox)control;
if (checkBox.Checked && checkBox.Tag is string)
{
string checkBoxId = (string)checkBox.Tag;
checkBoxesLine += string.Format("{0}, ", checkBoxId);
}
}
}
This is the button i am using to open the new form and move the checkbox tag data and textbox.text data to the new form.
private void code_blue_link_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
trouble_shooting = tshooting_text.Text;
services_offered = services_offered_text.Text;
other_notes = other_notes_text.Text;
cust_modem = cust_modem_text.Text;
//Opens CODE BLUE form and pushes text to it.
code_blue_form CBForm = new code_blue_form();
CBForm.cust_name_cb = cust_name_text.Text;
CBForm.cust_cbr_cb = cust_callback_text.Text;
CBForm.cust_wtn_cb = cust_btn_text.Text;
CBForm.cust_notes_cb = cust_modem + "\r\n" + trouble_shooting + "\r\n" + services_offered + "\r\n" + other_notes;
CBForm.Show();
}
Here is my code for the Second form and how i am getting the information to populate textboxes on that form.
public partial class code_blue_form : Form
{
public string cust_name_cb;
public string cust_wtn_cb;
public string cust_cbr_cb;
public string cust_notes_cb;
public string cust_modem_cb;
public code_blue_form()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
cb_name_text.Text = cust_name_cb;
cb_wtn_text.Text = cust_wtn_cb;
cb_cbr_text.Text = cust_cbr_cb;
cb_notes_text.Text = cust_notes_cb;
}
}
}
Please forgive the long post! Any ideas/direction on this would be greatly appreciated. Thanks!
I am not going to answer straight away using ur code. I find code smell. If I were you I would do this (but then if you are adamant about going with the same design, then you can tweak my code accordingly, no big deal, the bottom line is you get the idea how to do):
void code_blue_link_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
var checkBoxIds = GetCheckBoxIds();
cust_modem = cust_modem_text.Text;
trouble_shooting = tshooting_text.Text;
services_offered = services_offered_text.Text;
other_notes = other_notes_text.Text;
//take off underscore convetion and replace with camelCase convention.
CodeBlueForm cbForm = new CodeBlueForm(checkBoxIds, cust_name_text.Text,
cust_callback_text.Text,
cust_btn_text.Text,
cust_modem + "\r\n" +
trouble_shooting + "\r\n" +
services_offered + "\r\n" +
other_notes);
cbForm.Show();
}
private List<int> GetCheckBoxIds()//even better naming required like GetFruitIds()
{ //(whatever the id is of) or even better Tag
//checkBoxes with the Fruit object iself and not ids.
List<int> checkBoxIds = new List<int>(); //So you can call GetFruits();
foreach (Control control in pnlCheckBoxes.Controls)
{
if (control is CheckBox)
{
CheckBox checkBox = (CheckBox)control;
if (checkBox.Checked && checkBox.Tag is int) //tag them as ints.
checkBoxIds.Add((int)checkBox.Tag); //I hope ids are integers.
}
}
return checkBoxIds;
}
public partial class CodeBlueForm : Form
{
List<int> checkBoxIds = new List<int>():
string cust_cbr_cb; //should be private.
string cust_name_cb;
string cust_wtn_cb;
string cust_notes_cb;
string cust_modem_cb;
public CodeBlueForm(List<int> ids, string cust_name_cb, string cust_wtn_cb,
string cust_notes_cb, string cust_modem_cb)
{
InitializeComponent();
this.checkBoxIds = ids;
this.cust_name_cb = cust_name_cb;
this.cust_wtn_cb = cust_wtn_cb;
this.cust_notes_cb = cust_notes_cb;
this.cust_modem_cb = cust_modem_cb;
}
private void button1_Click(object sender, EventArgs e)
{
cb_name_text.Text = cust_name_cb;
cb_wtn_text.Text = cust_wtn_cb;
cb_cbr_text.Text = cust_cbr_cb;
cb_notes_text.Text = cust_notes_cb;
string checkBoxesLine = "\u2022 LIGHTS ";
// if you dont require a lot of string formatting, then just:
checkBoxesLine += string.Join(", ", checkBoxIds);
// or go with your classical:
//foreach (int id in checkBoxIds)
// checkBoxesLine += string.Format("{0}, ", checkBoxIds);
//and do what u want with checkboxline here.
}
}

Categories