I'm new to C# and I really need to know how to call/use a string from another method.
For example:
public void button1_Click(object sender, EventArgs e)
{
string a = "help";
}
public void button2_Click(object sender, EventArgs e)
{
//this is where I need to call the string "a" value from button1_click
string b = "I need ";
string c = b + a;
}
In this example I need to call string "a" defined in function button1_Click() from function button2_Click()
Usually you'd pass it as an argument, like so:
void Method1()
{
var myString = "help";
Method2(myString);
}
void Method2(string aString)
{
var myString = "I need ";
var anotherString = myString + aString;
}
However, the methods in your example are event listeners. You generally don't call them directly. (I suppose you can, but I've never found an instance where one should.) So in this particular case it would be more prudent to store the value in a common location within the class for the two methods to use. Something like this:
string StringA { get; set; }
public void button1_Click(object sender, EventArgs e)
{
StringA = "help";
}
public void button2_Click(object sender, EventArgs e)
{
string b = "I need ";
string c = b + StringA;
}
Note, however, that this will behave very differently in ASP.NET. So if that's what you're using then you'll probably want to take it a step further. The reason it behaves differently is because the server-side is "stateless." So each button click coming from the client is going to result in an entirely new instance of the class. So having set that class-level member in the first button click event handler won't be reflected when using it in the second button click event handler.
In that case, you'll want to look into persisting state within a web application. Options include:
Page Values (hidden fields, for example)
Cookies
Session Variables
Application Variables
A Database
A Server-Side File
Some other means of persisting data on the server side, etc.
You need to declare string a in the scope of the class, not the method, at the moment it is a "local variable".
Example:
private string a = string.Empty;
public void button1_Click(object sender, EventArgs e)
{
a = "help";
}
public void button2_Click(object sender, EventArgs e)
{
//this is where I need to call the string "a" value from button1_click
string b = "I need";
string c = b + a;
}
You can now access the value of your "private field" a from anywhere inside your class which in your example will be a Form.
Agree with #Devid 's answer but I prefer to create a class of required entities and then use them in entire solution without passing variable as argument.
Classname.variableName;
for ex-
Class argumentData{
public static string firstArg= string.Empty;
public static string secArg= string.Empty;
}
Say I am assigning data in function
void assignData()
{
argumentData.firstArg="hey";
argumentData.secArg="hello";
}
if I want to use it in another method then
void showData()
{
Console.WriteLine("first argument"+argumentData.firstArg);
Console.WriteLine("sec argument"+ argumentData.secArg);
}
Hope this helps!
Refactor that into a method call (or property) so you can access the value of a elsewhere in your application:
public String GetStringAValue() {
return "help";
}
public void button1_Click(object sender, EventArgs e) {
string a = GetStringAValue();
}
public void button2_Click(object sender, EventArgs e) {
string a = GetStringAValue();
string b = "I need";
string c = b + a;
}
Also note that you could be using implicit type declarations. In effect, these are equivalent declarations:
string a = GetStringAValue();
var a = GetStringAValue();
class SomeClass
{
//Fields (Or Properties)
string a;
public void button1_Click(object sender, EventArgs e)
{
a = "help"; //Or however you assign it
}
public void button2_Click(object sender, EventArgs e)
{
string b = "I need";
string c = b + (a ?? String.Empty); //'a' should be null checked somehow.
}
}
make is a class level variable (global variable) or create a getter and setter for String a, to name a couple options.
You can't do that. string a is a local variable declaration. It's called "local" because it is only accessible "locally" to the block in which it occurs.
To make the variable visible to both methods, you can create a field in the class containing the methods. If the methods are in different classes, though, the solution gets more complicated.
You can't do this because those variables are in different scopes (think it as being hidden). The only way to achieve this is to move a in the main form class:
public partial class Form1 : Form
{
string a;
// etc ...
}
you can use session here
public void button1_Click(object sender, EventArgs e)
{
string a = "help";
Session["a"]=a;
}
public void button2_Click(object sender, EventArgs e)
{
string d=Session["a"].ToString();
string b = "I need ";
string c = b + d;
}
You could save the variable into a file, then access the file later, like this:
public void button1_Click(object sender, EventArgs e)
{
string a = "help";
File.WriteAllText(#"C:\myfolder\myfile.txt", a); //Change this to your real file location
}
public void button2_Click(object sender, EventArgs e)
{
string d = File.ReadAllText(#"C:\myfolder\myfile.txt");
//this is where I need to call the string "a" value from button1_click
string b = "I need";
string c = b + d; //Instead of a, put the variable name (d in this case)
}
If you do that, just make sure to put this in your code: using System.IO;
Is there any way, within a WinForms solution, to have one Button's function be referenced in a different Form under a different Button?
An example of this would be:
Form1.cs:
public static int math = -1;
public void button1_Click(object sender, EventArgs e)
{
textBox1.Text = "How to make this work";
pictureBox1.Image = Image.FromFile("Confused.jpg");
math++;
}
Form2.cs:
public void button1_Click(object sender, EventArgs e)
{
Form1.button1_Click(sender, e);
}
Referencing the Form1.button1_Click does not seem to work, giving me an error:
An object reference is required for the non-static field, method, or
property 'Form1.button1_Click(object, EventArgs)'
Any help would be greatly appreciated!
I am new to ASP.NET and I am trying to set session variable. I have one form (SelectPlayer.aspx) where I am trying to set the session but when I try to see the result on second page it does not show me any value. Below is my code.
SelectPlayer.aspx
public partial class SelectPlayer : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Session["player1"] == null)
{
lblSelectPlayer.Text = "Select Player 1";
}
}
protected void btnSelect_Click(object sender, EventArgs e)
{
Session["player1"] = "PlayerSession";
Response.Redirect("Score.aspx");
}
}
Score.aspx
protected void Page_Load(object sender, EventArgs e)
{
if (Session["player1"] == null)
{
Response.Redirect("SelectPlayer.aspx");
}
}
Change Response.Redirect("Score.aspx"); to Response.Redirect("Score.aspx", true);
The second parameter of a redirect indicates that you want to end the response. I've found in the past that setting a Session directly before doing a redirect without this second parameter can cause issues.
I have created a composite control with sample details as follows. Basically, the first time on page load the control sets a view state variable and the problem is that on post back (when the button is clicked), the ViewState variable is null. I have researched extensively and I am not able to find a solution. I checked all the Microsoft recommended articles and also from other developers. This approach seem to work for everyone and I can't figure out what I'm doing wrong. If anyone can help, I would really appreciate it.
PS: This code may not work as it is only for illustrative purposes. but this is exactly what i'm doing in my code.
Public class Test : CompositeControl
{
private Button btnTest = new Button();
public string TestViewState
{
get
{
string s = (string)ViewState["test"];
return (s == null) ? String.Empty : s;
}
set
{
ViewState["test"] = value;
}
}
private void set()
{
TestViewState = "test";
}
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
set();
}
protected override void RecreateChildControls()
{
EnsureChildControls();
}
protected override void CreateChildControls()
{
base.Controls.Clear();
btnTest.ID = "btnTest";
btnTest.Click += new EventHandler(btnSubmitTest_Click);
if (!ChildControlsCreated)
Controls.Add(btnTest);
base.CreateChildControls();
}
protected override void Render(HtmlTextWriter writer)
{
btnSumbit.Render(writer);
}
protected void btnSubmitTest_Click(object sender, EventArgs e)
{
string test = TestViewState; // Viewstate value is null here!!!!!!
}
}
Are you sure that Page_Load is getting called? As far as I can remember that "notation" works only on pages and User Controls (didn't check that). Try overriding:
protected override void OnLoad(EventArgs e)
{
...
}
Test it with a Debugger.
Ok, the enableviewstate was disabled at the web.config level by another team member. Glad I found it. Thanks Arthur for confirming it worked for you.
I am building a Asp.net Application. I need to save a HashTable in a session.
At page load i am writing
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Session["AttemptCount"]=new Hashtable(); //Because of this line.
}
}
Here problem is, when a user refresh the page, session["AttemptCount"] also get refreshed.
I want to know where should I declare
Session["AttemptCount"]=new Hashtable();
So that my seesion do not get refeshed.
EDIT In Global.asax, this session will get started, as soon as user opens the website. I want to creat this session only if user go to a particular page. i.e Login.aspx
Do it in the Session_Start method in your Global.asax like so...
protected void Session_Start(object sender, EventArgs e)
{
Session["AttemptCount"]=new Hashtable();
}
Update:
Then simply just do a check to see if the session variable exists, if it doesn't only then create the variable. You could stick it in a property to make things cleaner like so...
public Hashtable AttemptCount
{
get
{
if (Session["AttemptCount"] == null)
Session["AttemptCount"]=new Hashtable();
return Session["AttemptCount"];
}
}
And then you could just call on the property AttemptCount wherever you need like so...
public void doEvent(object sender, EventArgs e)
{
AttemptCount.Add("Key1", "Value1");
}
You could make a property like this in your page:
protected Hashtable AttemptCount
{
get
{
if (Session["AttemptCount"] == null)
Session["AttemptCount"] = new Hashtable();
return Session["AttemptCount"] as Hashtable;
}
}
then you can use it without having to worry:
protected void Page_Load(object sender, EventArgs e)
{
this.AttemptCount.Add("key", "value");
}
test if it exists first
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if(Session["AttemptCount"] == null)
{
Session["AttemptCount"]=new Hashtable(); //Because of this line.
}
}
}
though the session_start is better, you only need to uses it on one page but you can create it for each session.
Hashtable hastable_name=new Hashtable()
Session["AttemptCount"]=hastable_name
Look at Global.asax and the Application_Started (I think) and there is one for session started too.