xxxx Does not exist in this current context [closed] - c#

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I keep getting the error
" XXXX does not exist in this current context".
I know there are plenty of similar questions, but they don't help me as I'm not very good at C# & asp.net.
I've been struggling with this piece of code. Basically I need to have a calculate cost (Which is mean tot be done in the Beverage class, and it outputted on the About page.
My code is very messy as I honestly have next to no idea what I'm doing.
Beverage class:
public class Beverage
{
string fruit;
int kg;
int cost;
int cal;
public string getOutputString()
{
return " Your selected Beverage is made of " + kg + " of " + fruit + ". " +
"The cost is £ " + cost + " and has " + cal + ".";
}
public static int CalculatePrice()
{
int cost = (TextBox1.text + TextBox2.text);
int cal = TextBox1.Text + TextBox3.Text;
}
}
About code behind:
public partial class About : Page
{
protected void Page_Load(object sender, EventArgs e)
{
MyFruit = Session["Fruitname"] as List<string>; //Create new, if null
if (MyFruit == null)
MyFruit = new List<string>();
DropDownList1.DataSource = MyFruit;
DropDownList1.DataBind();
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
{
decimal total = calculatePrice(DropDownList1.SelectedItem.Text,
TextBox1.Text.Trim());
lbl1.Text = "You would like " + TextBox1.Text.Trim() +
DropDownList1.SelectedItem.Text + "(s) for a total of $" +
total.ToString();
}
}
public List<string> MyFruit { get; set; }
}
The errors are always for TextBox1, TextBox2, TextBox3 & calculatePrice.

You are getting the error because you are trying to access TextBox1.Text outside About class. Only this class will have access to this properties, as it inherits System.Web.UI.Page. TextBox1.Text doesn't have its scope in Beverage class. If you want to use these values in that class, pass them as input parameters to the method.

Related

How to return items from a list according to their respective checked box in checkedlistbox C#?

I have made progress on my first C# app from another answer but I still cannot wrap my head around the next part.
I have a JSON file with an array that contains my data. My app takes info from a JSON file containing an array and populates my checkedlistbox1 with the "Name" of each Finding. When you click on any item in the checkedlistbox1 (not check), it shows that particular Finding's info (name,risk,description,recommendation defined as "CompleteFinding") in the adjacent richtextbox1. All that is great.
What I want to do now is grab whichever items' CompleteFinding that are checked in my checkedlistbox1 and do what I want with it i.e. a variable or something to be referenced in a textbox or outputted elsewhere later when Button1 is clicked etc. I tried using "checkedlistbox1.SelectedItems" and am getting an error about converting to my Findings type. I also tried using a foreach loop and it only returns the last item that is checked. I need each checked items' CompleteFinding to use when Button1 is clicked.
JSON File Example Content:
[
{
"Name": "Test Name 1",
"Risk": "Low",
"Details": "Detailed description",
"Recommendation": "Recommended action"
},
{
"Name": "Test Name 2",
"Risk": "Low",
"Details": "Detailed description",
"Recommendation": "Recommended action"
}
]
Code
public partial class Form1 : Form
{
public class Findings
{
[JsonProperty("Name")]
public string Name { get; set; }
[JsonProperty("Risk")]
public string Risk { get; set; }
[JsonProperty("Details")]
public string Details { get; set; }
[JsonProperty("Recommendation")]
public string Recommendation { get; set; }
public string CompleteFinding
{
get
{
return "Name:" + "\n" + Name + "\n" + "\n" + "Risk:" + "\n" + Risk + "\n" + "\n" + "Details:" + "\n" + Details + "\n" + "\n" + "Recommendation:" + Recommendation + "\n";
}
}
}
public Form1()
{
InitializeComponent();
var json = JsonConvert.DeserializeObject<List<Findings>>(File.ReadAllText(#"findings-array.json"));
checkedListBox1.DataSource = json;
checkedListBox1.DisplayMember = "Name";
}
private void Button1_Click(object sender, System.EventArgs e)
{
//would like to be able to use the CompleteFinding of each checkeditem here.
}
private void checkedListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
//This populates a single Finding's CompleteFinding to the richtextbox.
richTextBox1.Text = ((Findings)checkedListBox1.SelectedItem).CompleteFinding;
}
}
Something like this, perhaps?
private void Button1_Click(object sender, System.EventArgs e) {
richTextBox1.Text = null; // clear out your results first
var sb = new StringBuilder();
foreach (var item in checkedListBox1.SelectedItems) {
var selected = (Findings)item;
sb.AppendLine(selected.CompleteFinding);
sb.AppendLine(); // adds a blank line
}
richTextBox1.Text = sb.ToString();
}
From your comment below, it sounds like your ListView is written so that it uses physical checkboxes. That is something you probably should have mentioned in your original question.
To write the code so that it only looks at ListViewItems that have check marks on them, use something like this:
private void Button1_Click(object sender, System.EventArgs e) {
richTextBox1.Text = null; // clear out your results first
var sb = new StringBuilder();
foreach (ListViewItem item in checkedListBox1.Items) {
if (item.Checked) {
var find = item.Tag as Finding;
if (find != null) {
sb.AppendLine(find.CompleteFinding);
sb.AppendLine(); // adds a blank line
}
}
}
richTextBox1.Text = sb.ToString();
}
I do not know how JSON attaches to individual ListViewItems. In the code above, I have shown it pulling the data from a Tag field, but it would only be there if you wrote it there. There are lots of ways to write code.
I have been assuming that this is a basic Windows Forms application. The ListView control for Windows Forms is different from the one available for Web Applications.

using a try catch statement to keep a text box cleared

I am making a windows form application that takes various game entries (title,genre,price) and then stores them in an array with a maximum of four entries.
The error I am having is that if there are no values entered in my text boxes, I want a message box to appear to force the user to enter values. This happens.
The problem is that after this, it does not give the user another try. It just stops the program. I have tried using a try catch statement to do this but I am not quite sure how to use this. Would this be the correct solution?
namespace gameForm
{
public partial class gameEntryForm : Form
{
public gameEntryForm()
{
InitializeComponent();
}
struct Game
{
public string Title;
public string Genre;
public decimal Price;
}
static Game[] aNewGame = new Game[4]; //max size of the array is 4
static int newGameEntryIndex = 1;
private void gameEntryForm_Load(object sender, EventArgs e)
{
aNewGame[0].Title = "golf tour"; //this is a game already stored in the database
aNewGame[0].Genre = "sports";
aNewGame[0].Price = 1.99m;
}
private void btnSave_Click(object sender, EventArgs e)
{
try
{
if (String.IsNullOrEmpty(tbGenre.Text))
{
MessageBox.Show("please enter a Game genre.");
}
if (String.IsNullOrEmpty(tbTitle.Text))
{
MessageBox.Show("please enter a Game title");
}
if (String.IsNullOrEmpty(tbPrice.Text))
{
MessageBox.Show("please enter a Game price");
}
}
//catch()
//{
//}
aNewGame[newGameEntryIndex].Title = tbTitle.Text;
aNewGame[newGameEntryIndex].Genre = tbGenre.Text;
aNewGame[newGameEntryIndex].Price = Convert.ToDecimal(tbPrice.Text);
newGameEntryIndex++;
MessageBox.Show("entry saved");
//clears the text boxes
tbTitle.Clear();
tbGenre.Clear();
tbPrice.Clear();
}
private void btnShow_Click(object sender, EventArgs e)
{
rtbShow.Text = "Game Details \n\nGame 1 \n" + aNewGame[0].Title + "\n" + aNewGame[0].Genre + "\n" + aNewGame[0].Price + "\n\n" + "Game 2 \n" + aNewGame[1].Title + "\n" + aNewGame[1].Genre + "\n" + aNewGame[1].Price + "\n\n" + "Game 3 \n" + aNewGame[2].Title + "\n" + aNewGame[2].Genre + "\n" + aNewGame[2].Price + "\n\n" + "Game 4 \n" + aNewGame[3].Title + "\n" + aNewGame[3].Genre + "\n" + aNewGame[3].Price; ;
}
//clears the rich text box
private void btnClear_Click(object sender, EventArgs e)
{
rtbShow.Clear();
}
private void btnQuit_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}
Add a return, no try/catch required:
if (String.IsNullOrEmpty(tbGenre.Text))
{
MessageBox.Show("please enter a Game genre.");
return; // Exit current function
}
Try/catch is for when you have exceptions.
Try-Catch is of no use to you.
What you should do is in the btnSave_Click method return when the textboxes are not populated:
if (String.IsNullOrWhiteSpace(tbGenre.Text) ||
String.IsNullOrWhiteSpace(tbTitle.Text) ||
String.IsNullOrWhiteSpace(tbPrice.Text)
{
MessageBox.Show("Please enter a game genre, game title and game price.");
return;
}
aNewGame[newGameEntryIndex].Title = tbTitle.Text;
...
There is another solution you could do. Only activate the Save-button if all three textboxes has values in them.
Something like:
private void ValidateGameData(object sender, EventArgs e)
{
if (String.IsNullOrWhiteSpace(tbGenre.Text) ||
String.IsNullOrWhiteSpace(tbTitle.Text) ||
String.IsNullOrWhiteSpace(tbPrice.Text))
{
btnSave.Enabled = false;
}
else
{
btnSave.Enabled = true;
}
}
tbGenre.TextChanged += ValidateGameData;
tbTitle.TextChanged += ValidateGameData;
tbPrice.TextChanged += ValidateGameData;
In your code for btnSave_Click you are testing the value of the various TextBoxes and displaying a message if they are NULL or empty.
However, you continue execution of your code even if they are NULL or empty.
You should stop processing more code if the conditions fail so that you don't try to use the NULL\empty values.
Something like:
private void btnSave_Click(object sender, EventArgs e)
{
if (String.IsNullOrEmpty(tbGenre.Text))
{
MessageBox.Show("please enter a Game genre.");
}
else if (String.IsNullOrEmpty(tbTitle.Text))
{
MessageBox.Show("please enter a Game title");
}
else if (String.IsNullOrEmpty(tbPrice.Text))
{
MessageBox.Show("please enter a Game price");
}
else
{
// You forgot to create the new game at this index
aNewGame[newGameEntryIndex] = new Game();
aNewGame[newGameEntryIndex].Title = tbTitle.Text;
aNewGame[newGameEntryIndex].Genre = tbGenre.Text;
aNewGame[newGameEntryIndex].Price = Convert.ToDecimal(tbPrice.Text);
newGameEntryIndex++;
MessageBox.Show("entry saved");
//clears the text boxes
tbTitle.Clear();
tbGenre.Clear();
tbPrice.Clear();
}
}
I've also added a line:
aNewGame[newGameEntryIndex] = new Game();
As I couldn't see anywhere that you created the new Game object before trying to set it's properties.

C#, Write in a .txt file, without deleting the previous line [duplicate]

This question already has answers here:
Open existing file, append a single line
(9 answers)
Closed 4 years ago.
Basicly I'm writing a fake malware, which will write in a .txt the Session username of the person which clicked on it. The problem is that when someone execute it will erase the previous lines.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.Text = "Fake Malware";
}
private void Form1_Load(object sender, EventArgs e)
{
string createText = " just clicked on the fake Malware";
File.WriteAllText("//vm-files/users/ngallouj/zig/zig.txt", Environment.UserName + createText + " " + DateTime.Now.ToString("h:mm:ss tt"));
string readText = File.ReadAllText("//vm-files/users/ngallouj/zig/zig.txt");
}
private void zig(object sender, EventArgs e)
{
System.Diagnostics.Process.Start("Link to a warning message on click, nothing important.");
string createText = " just clicked on the fake Malware";
File.WriteAllText("//vm-files/users/ngallouj/zig/zig.txt", Environment.UserName+ createText + " " + DateTime.Now.ToString("h:mm:ss tt"));
string readText = File.ReadAllText("//vm-files/users/ngallouj/zig/zig.txt");
}
}
I think what you are looking for is AppendAllText:
File.AppendAllText("//vm-files/users/ngallouj/zig/zig.txt", "Wow it worked :)");
Here is the fix
private void Form1_Load(object sender, EventArgs e)
{
string createText = " just clicked on the fake Malware";
File.AppendAllText("//vm-files/users/ngallouj/zig/zig.txt", Environment.UserName + createText + " " + DateTime.Now.ToString("h:mm:ss tt"));
string readText = File.ReadAllText("//vm-files/users/ngallouj/zig/zig.txt");
}
private void zig(object sender, EventArgs e)
{
System.Diagnostics.Process.Start("#");
string createText = " just clicked on the fake Malware";
File.AppendAllText("//vm-files/users/ngallouj/zig/zig.txt", Environment.UserName+ createText + " " + DateTime.Now.ToString("h:mm:ss tt"));
string readText = File.ReadAllText("//vm-files/users/ngallouj/zig/zig.txt");
}
}
}

C# calling a decimal method with arguments in a form

So I am trying to do this for a hw and in my class I have this double method for converting from cm to inch:
public decimal Conversion(decimal Input)
{
return Input * (decimal)0.393701;
}
The problem is when I try to call it in a form, and I need to send arguments to it.
public partial class frmCmVoInch : Form
{
public frmCmVoInch()
{
InitializeComponent();
}
public frmCmVoInch(mainForm parent)
{
InitializeComponent();
MdiParent = parent;
}
private void btnKonverzija_Click(object sender, EventArgs e)
{
decimal parsed;
decimal.TryParse(txtVlez.Text, out parsed);
CmVoInch cmVoInch = new CmVoInch(decimal.Parse(txtVlez.Text));
rtbIzlez = txtVlez.Text + " cm = " + cmVoInch.Konverzija(parsed);
}
}
This is basically a typo:
rtbOutp = txtInp.Text + " cm = " + CmVoInch.Conversion(decimal.Parse(txtInp.Text));
Should be:
rtbOutp = txtInp.Text + " cm = " + cmVoInch.Conversion(decimal.Parse(txtInp.Text));
Note the change in case of CmVoInch. The first is the type name, so attempts to call an instance method without an instance, hence the error an object reference is required for the nonstatic field method or property. The second correctly refers to the instance of that class you created on the previous line.
You also need to change to set the text property of the RichTextBox, as you can't assign a string to it:
rtbOutp.Text = txtInp.Text + " cm = " + cmVoInch.Conversion(decimal.Parse(txtInp.Text));
but it is String, and it wont accept it even if I convert it to
decimal. Any way I can fix this?
the issue is not with the Conversion method.
the issue is the btnKonverzija_Click method returns void and you're trying to return a string value. you cannot do that.
private void btnKonverzija_Click(object sender, EventArgs e)
{
CmVoInch cmVoInch = new CmVoInch(decimal.Parse(txtInp.Text));
return txtInp.Text + " cm = " + CmVoInch.Conversion(decimal.Parse(txtInp.Text));
}
note - C# is a case-sensitive language, currently, you're calling the Converion method as if it belongs to a class rather you should use cmVoInch.Conversion not CmVoInch.Conversion.
full solution:
private void btnKonverzija_Click(object sender, EventArgs e)
{
CmVoInch cmVoInch = new CmVoInch(decimal.Parse(txtInp.Text));
rtbIzlez.Text = txtInp.Text + " cm = " + cmVoInch.Conversion(decimal.Parse(txtInp.Text));
}

c# how to insert into database

I need help on this, I'm inserting file directory into the database but it does not take into account of the txtStoryTitle.Text in the database, for example, if I type HelloWorld in txtStoryTitle. It appears as Images/Story//(filename) instead of Images/Story/HelloWorld/(filename) in the DB. I am using MySQL (workbench).
please give me an advice/solutions on this, thanks in advance!
Here are the partial codes:
protected void AjaxFileUpload1_UploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
{
EnsureDirectoriesExist();
String filepathImage = (#"Images/Story/" + txtStoryTitle.Text + "/" + e.FileName);
AjaxFileUpload1.SaveAs(Server.MapPath(filepathImage));
Session["filepathImage"] = filepathImage;
}
public void EnsureDirectoriesExist()
{
if (!System.IO.Directory.Exists(Server.MapPath(#"Images/Story/" + txtStoryTitle.Text + "/")))
{
System.IO.Directory.CreateDirectory(Server.MapPath(#"Images/Story/" + txtStoryTitle.Text + "/"));
}
}
protected void btnDone_Click(object sender, EventArgs e)
{
if (Session["filepathImage"] != null)
{
string filepathImage = Session["filepathImage"] as string;
act.ActivityName = dropListActivity.SelectedItem.Text;
act.Title = txtStoryTitle.Text;
act.FileURL = filepathImage;
daoStory.Insert(act);
daoStory.Save();
}
As per your code.. the file path is "Images/Story/" + txtStoryTitle.Text + "/" + e.FileName"
and after providing txtStoryTitle.Text it saved as "Images/Story//FileName".. then it means txtStoryTitle.Text does'nt contain any text..
If its in .Net then make sure you set autopostback property of txtStoryTitle textbox to true.
and if it is already true then try to find out why this textbox does'nt resist its state.

Categories