Passing variables to another Webpage - c#

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

Related

Listbox Item holds data

Server 1 Server2 Server Config Screen
I am trying to make a video game server manager and I have run into an issue. I want the user to be able to have as many servers as they would like. However I cannot figure out through google searching and just regular messing around how to store the information that the user selects to become associated with the Server they create in the list. Basically when you make Server1 it takes the info you selected from the boxes on the config screen and uses them on the server selection page. But, when you make Server2, the configuration overwrites Server1's configuration. I know my code isn't even setup to be able to do this but I would appreciate a push in the right direction as to which type of code I should use.
Tl:dr I want config options to be associated with ServerX in the server list and each server should have unique settings.
public partial class Form1 : Form
{
//Variables
string srvName;
string mapSelect;
string difSelect;
public Form1()
{
InitializeComponent();
this.srvList.SelectedIndexChanged += new System.EventHandler(this.srvList_SelectedIndexChanged);
}
private void srvList_SelectedIndexChanged(object sender, EventArgs e)
{
if(srvList.SelectedIndex == -1)
{
dltButton.Visible = false;
}
else
{
dltButton.Visible = true;
}
//Text being displayed to the left of the server listbox
mapLabel1.Text = mapSelect;
difLabel1.Text = difSelect;
}
private void crtButton_Click(object sender, EventArgs e)
{
//Add srvName to srvList
srvName = namBox1.Text;
srvList.Items.Add(srvName);
//Selections
mapSelect = mapBox1.Text;
difSelect = difBox1.Text;
//Write to config file
string[] lines = { mapSelect, difSelect };
System.IO.File.WriteAllLines(#"C:\Users\mlynch\Desktop\Test\Test.txt", lines);
//Clear newPanel form
namBox1.Text = String.Empty;
mapBox1.SelectedIndex = -1;
difBox1.SelectedIndex = -1;
//Return to srvList
newPanel.Visible = false;
}
}
You mentioned in a recent comment that you had tried saving to a .txt file but it overwrote it anytime you tried to make an additional one. If you wanted to continue with your .txt approach, you could simply set a global integer variable and append it to each file you save.
//Variables
string srvName;
string mapSelect;
string difSelect;
int serverNumber = 0;
...
serverNumber++;
string filepath = Path.Combine(#"C:\Users\mlynch\Desktop\Test\Test", serverNumber.ToString(), ".txt");
System.IO.File.WriteAllLines(filepath, lines);
I think below source code will give you some idea about the direction. Let us start with some initializations:
public Form1()
{
InitializeComponent();
this.srvList.SelectedIndexChanged += new System.EventHandler(this.srvList_SelectedIndexChanged);
mapBox1.Items.Add("Germany");
mapBox1.Items.Add("Russia");
difBox1.Items.Add("Easy");
difBox1.Items.Add("Difficult");
}
This is the event handler of the "Create Server" button. It takes server parameters from the screen and writes to a file named as the server.
private void crtButton_Click(object sender, EventArgs e)
{
//Add srvName to srvList
srvName = namBox1.Text;
srvList.Items.Add(srvName);
//Selections
mapSelect = mapBox1.Text;
difSelect = difBox1.Text;
//Write to config file
string path = #"C:\Test\" + srvName + ".txt";
StreamWriter sw = new StreamWriter(path);
sw.WriteLine(mapSelect);
sw.WriteLine(difSelect);
sw.Flush();
sw.Close();
//Clear newPanel form
namBox1.Text = String.Empty;
mapBox1.SelectedIndex = -1;
difBox1.SelectedIndex = -1;
//Return to srvList
//newPanel.Visible = false;
}
And finally list box event handler is below. Method reads the server parameters from file and displays on the screen.
private void srvList_SelectedIndexChanged(object sender, EventArgs e)
{
if (srvList.SelectedIndex == -1)
{
dltButton.Visible = false;
}
else
{
dltButton.Visible = true;
}
string path = #"C:\Test\" + srvList.SelectedItem + ".txt";
StreamReader sr = new StreamReader(path);
//Text being displayed to the left of the server listbox
mapLabel1.Text = sr.ReadLine(); // mapSelect;
difLabel1.Text = sr.ReadLine(); // difSelect;
}
Please feel free to ask any questions you have.
I ended up figuring out the issue. Basically I ended up deciding on a write to a txt file and then read from it to display the contents of the file in the server select menu. I also added a delete button so you can delete the servers that you created. it does not have full functionality yet but it is there. So here it what I ended up with and it works perfectly. Thank you all for trying to help.
public partial class Form1 : Form
{
//Variables
string srvName;
string mapSelect;
string mapFile;
string difSelect;
string difFile;
int maxPlayers;
string plrSelect;
string plrFile;
string finalFile;
string basepath = System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
string fileName = "config.txt";
public Form1()
{
InitializeComponent();
this.srvList.SelectedIndexChanged += new System.EventHandler(this.srvList_SelectedIndexChanged);
}
private void srvList_SelectedIndexChanged(object sender, EventArgs e)
{
//Read Server Selection
string srvSelect = srvList.GetItemText(srvList.SelectedItem);
string srvOut = System.IO.Path.Combine(basepath, srvSelect, fileName);
mapFile = File.ReadLines(srvOut).Skip(1).Take(1).First();
difFile = File.ReadLines(srvOut).Skip(2).Take(1).First();
plrFile = File.ReadLines(srvOut).Skip(3).Take(1).First();
//Display Server Selection
if (srvList.SelectedIndex == -1)
{
dltButton.Visible = false;
}
else
{
dltButton.Visible = true;
mapLabel1.Text = mapFile;
difLabel1.Text = difFile;
plrLabel1.Text = plrFile;
}
private void crtButton_Click(object sender, EventArgs e)
{
//Set Server Name
srvName = namBox1.Text;
string finalpath = System.IO.Path.Combine(basepath, srvName);
//Check if server name is taken
if (System.IO.Directory.Exists(finalpath))
{
MessageBox.Show("A Server by this name already exists");
}
else
{
//Add Server to the Server List
srvList.Items.Add(srvName);
//Server Configuration
mapSelect = mapBox1.Text;
difSelect = difBox1.Text;
maxPlayers = maxBar1.Value * 2;
plrSelect = "" + maxPlayers;
//Clear New Server Form
namBox1.Text = String.Empty;
mapBox1.SelectedIndex = -1;
difBox1.SelectedIndex = -1;
//Create the Server File
Directory.CreateDirectory(finalpath);
finalFile = System.IO.Path.Combine(finalpath, fileName);
File.Create(finalFile).Close();
//Write to config file
string[] lines = { srvName, mapSelect, difSelect, plrSelect };
System.IO.File.WriteAllLines(#finalFile, lines);
//Return to srvList
newPanel.Visible = false;
}
}
}

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();
}
}

Rendering server control in a callback

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.

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.
}
}

Display all listview items in messagebox c#

I have a listview with subitems. The first 5 sub items are the name, items, total price, address and telephone.
The rest of the subitems contain the past list that I displayed for my order.
It is a pizzeria program and I want it to be able to get the customers info and order.
I can get the info but can't get the rest of the order.
I'm wondering how I can display the rest of my order if that makes sense.
Example Order:
Name: Claud
Items: 3
Total: 10.99
Address: (Blank)
Telephone: (Blank)
Order: Small Pizza
-Bacon
BreadSticks
Right now my messagebox looks like this:
Name: Claud
Items: 3
Total: 10.99
Address: (Blank)
Telephone: (Blank)
Order: Small Pizza
So I just want it to display the -Bacon and BreadSticks.
Source Code:
private void CustomerInfo_Click(object sender, EventArgs e)
{
ListViewItem customers = new ListViewItem(fullName.Text);
customers.SubItems.Add(totalcount.ToString());
customers.SubItems.Add(total.ToString());
customers.SubItems.Add(Address.Text);
customers.SubItems.Add(telephone.Text);
for (int i = 0; i < OrderlistBox.Items.Count; i++)
{
customers.SubItems.Add(OrderlistBox.Items[i].ToString());
}
Customers.Items.Add(customers);
MessageBox.Show("Sent order for " + fullName.Text.ToString() + " to screen.");
//CLEAR ALL FIELDS
OrderlistBox.Items.Clear();
fullName.Text = "";
Address.Text = "";
telephone.Text = "";
totalDue.Text = "";
totalItems.Text = "";
}
private void customerInformationToolStripMenuItem_Click(object sender, EventArgs e)
{
if (Customers.SelectedItems.Count != 0)
{
MessageBox.Show("Name: " + Customers.SelectedItems[0].SubItems[0].Text + "\n" +
"Adress: " + Customers.SelectedItems[0].SubItems[3].Text + "\n" +
"Telephone: " + Customers.SelectedItems[0].SubItems[4].Text + "\n" +
"Order: " +Customers.SelectedItems[0].SubItems[5].Text);
}
}
You can create custom message box by creating new winform that act as your messagebox.
Create public property on it to pass the value of your selecteditems something like:
Then on your form :
private void customerInformationToolStripMenuItem_Click(object sender, EventArgs e)
{
if (Customers.SelectedItems.Count != 0)
{
var myformmessagedialog = new MyFormMessageDialog
{
name = Customers.SelectedItems[0].SubItems[0].Text,
adress=Customers.SelectedItems[0].SubItems[3].Text,
telephone=Customers.SelectedItems[0].SubItems[4].Text
};
myformmessagedialog.ShowDialog();
}
}
Your MessageBoxDialogform:
MyFormMessageDialog : Form
{
public MyFormMessageDialog()
{
InitializeComponent();
}
public string name;
public string adress;
public string telephone;
private void MyFormMessageDialog_Load(object sender, EventArgs e)
{
lblName.Text = name;
lbladdress.Text = adress;
telephone.Text telephone;
//if you are saving ado.net stuff
//query username where name = name then bind it on a list box or a combo box
var Orderdata = //you retrieve info via DataTable;
lstOder.Items.Clear();
foreach (DataRow data in Orderdata.Rows)
{
var lvi = new ListViewItem(data["Order"].ToString());
// Add the list items to the ListView
lstlstOder.Items.Add(lvi);
}
}
}
Hope this help you.
Regards

Categories