Reference an ASP control inside a function or class method - c#

How do you reference an asp.net control on your page inside a function or a class.
private void PageLoad(object sender, EventArgs e)
{
//An example control from my page is txtUserName
ChangeText(ref txtUserName, "Hello World");
}
private void ChangeText(ref HtmlGenericControl control, string text)
{
control.InnerText = text;
}
Will this actually change the text of the txtUserName control?
I tried this and is working
private void PageLoad(object sender, EventArgs e)
{
ChangeText(txtUserName, "Hello World");
}
private void ChangeText(TextBox control, string text)
{
control.Text = text;
}

Yes, it should, assuming it's at the appropriate point in the page lifecycle, so that nothing else messes with it afterwards. (I don't know the details of ASP.NET lifecycles.
However, it's worth mentioning that there's absolutely no reason to pass it by reference here. It suggests that you don't fully understand parameter passing in .NET - I suggest you read my article on it - once you understand that (and the reference/value type distinction) all kinds of things may become easier for you.
Of course, if you've already tried the code given in the question and found it didn't work, please give more details. Depending on the type of txtUserName, it could even be that with ref it won't compile, but without ref it will just work.

Unless I'm missing something, all you need to do is this:
private void PageLoad(object sender, EventArgs e)
{
txtUserName.Text = "Hello World";
}

Related

Why cant I change the SelectedIndex of a combobox from the perspective of another form?

I'm pretty new to C# programming so please forgive my probably super bad mistakes. I have a combobox in SuperAdventure.cs (cboWeapons) and I cant seem to change it from the level of the second form (InventoryScreen.cs) via the following button:
private void btnEquipWeapon_Click(object sender, EventArgs e)
{
SuperAdventure weapon = new SuperAdventure();
String CurrentWeapon = this.cboCurrentWeapon.GetItemText(this.cboCurrentWeapon.SelectedItem);
weapon.cboWeapons_SelectedItemChange(CurrentWeapon);
}
And here is the cboWeapons_SelectedItemChange method from SuperAdventure.cs:
public void cboWeapons_SelectedItemChange(string weapon)
{
cboWeapons.SelectedIndex = cboWeapons.FindString(weapon);
}
The cboWeapons combobox is data bound but I believe that would not make too much of a difference in this case? Also, I was able to change it using a test button I made in SuperAdventure form by just:
private void btnChange(object sender, EventArgs e)
{
cboWeapons.SelectedIndex = cboWeapons.FindString("Sword");
}
And yes, I am making a silly RPG based on Scott Lilly's tutorial in C# with mostly my own forms classes etc... Hope someone will be able to help! Thanks in advance!
An easy solution (I would not really recommend for big projects) would be like this: First, add a private field in InventoryScreen of the SuperAdventure form type. Then add SuperAdventure type to your constructor of InventoryScreen. This way when you call InventoryScreen you will pass your SuperAdventure handler to the new InventoryScreen and from that handle you can make changes to the original existing SuperAdventure form.
SuperAdventure callingForm;
InventoryScreen(Player player, SuperAdventure callingForm) {
InitializeComponent();
_currentPlayer = player;
this.callingForm = callingForm;
cboCurrentWeapon.DataSource = _currentPlayer.Weapons;
cboCurrentWeapon.DisplayMember = "Name";
}
When you call InventoryScreen just pass this as another parameter like:
InventoryScreen iv = new InventoryScreen(player, this);
Finally, the button in InventoryScreen would change to:
private void btnEquipWeapon_Click(object sender, EventArgs e)
{
String CurrentWeapon = this.cboCurrentWeapon.GetItemText(this.cboCurrentWeapon.SelectedItem);
callingForm.cboWeapons_SelectedItemChange(CurrentWeapon);
}
Form1.ComboBox1.SelectedIndex = me.ComboBox2.SelectedIndex
Thats in vb.net but you can translate and try i think

C# Unable To Change Components Of Form From Another Class

Before I start, I'd like to say that I have looked for an answer for this over the internet for quite a while, and unable to come to a solution. I know how to solve this, but it doesn't want to work.
Here's what I know: Assuming that I have a label and another class, if I want to manipulate the label I need to create an instance of the form that has the label, call the method of the new class with the form, and then call the method from within the form class that changes the label. This is what I have.
This is from the form class
private void button1_Click(object sender, EventArgs e)
{
Question steve = new Question(1, 1, "nothing", new string[] {});
steve.Show(new Form1(), "I win");
}
public void ChangeLabel(string s)
{
this.lblTest.Text = s;
}
And this is the Question class
public void Show (Form1 f, string str)
{
f.ChangeLabel(str);
}
Syntax-wise this is correct, and when running the debugger lblTest.Text did equal "I win", but there were no visual changes on the form.
P.S. I am in high school and still learning C#, so if I made any mistakes in my explanation or the code, please point them out. Also, disregard the Question constructor, it's useless right now.
Thanks
No ! you don't need to create new instance of the form.
You must pass the current instance using this keyword:
private void button1_Click(object sender, EventArgs e)
{
Question steve = new Question(1, 1, "nothing", new string[] {});
steve.Show(this, "I win"); //change it
}

Making two boxes equal each other

I am trying to make a text box (UPC_txtBox4) self populate to equal the same value of UPC_txtBox2. The two text boxes are on separate forms but I feel there should be a way to link the two.
If form1 is responsible for navigating to form2, then you can pass the value on the query string from form1 using a URL similar to the following:
protected void Page_Load(object sender, EventArgs e)
{
if (this.IsPostBack)
{
Response.Redirect(Request.ApplicationPath + "/Form2.aspx?upc=" + UPC_txtBox2.Text, false);
}
}
then in form2 code:
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
// Assuming this field is an asp.net textbox and not an HTML input
UPC_txtBox4.Text = Request.QueryString["upc"];
}
}
Alternatively, you could store the value in session state, assuming that you are using sessions.
CORRECTION: Seeing as you are using WebForms, not WinForms as I had assumed, the below is irrelevant. I'll leave it just incase it helps someone else.
You should just create a method on the form that needs to be updated, then pass a reference when of that form to the newly created form.
This won't work if either form is a dialog (as far as I know).
So:
Form that has the textbox that will be directly edited.
private Form formToUpdate;
public void OpenForm(Form _formToUpdate)
{
formToUpdate = _formToUpdate;
txtBlah.TextChanged += new EventHandler(OnTextChanged);
this.Show();
}
private void OnTextChanged(object sender, EventArgs e)
{
formToUpdate.UpdateText(txtBlah.Text);
}
Form that is to be dynamically updated:
delegate void StringParameterDelegate (string value);
public void UpdateText(string textToUpdate)
{
if (InvokeRequired)
{
BeginInvoke(new StringParameterDelegate(UpdateText), new object[]{textToUpdate});
return;
}
// Must be on the UI thread if we've got this far
txtblah2.Text = textToUpdate;
}
Note: this is untested (although it should work), and largely pseudo code, you'll need to tailor it to your solution obviously.

At what point in my code did this List<> become empty?

namespace Messages
{
public partial class Email
{
List<Document> attachments = new List<Document>();
protected void Page_Load(object sender, EventArgs e)
{
foreach(Document document in documentList)
{
attachments.Add(document);
}
}
protected void btnSend_Click(object sender, EventArgs e)
{
sendMail(attachments);
}
}
}
As you can guess, I've stripped this code right down for explanation purposes but that's pretty much all I'm doing with it. I've got a feeling it's to do with deep/shallow copying and cloning, if so - can someone help explain what's gone on here and how I can avoid it/populate the list differently.
Thanks a lot,
Dan
EDIT: Sorry, where I've wrote 'documentList' it actually reads:
(List<Document>)Session[Request.QueryString["documentList"]]
So yer - it's coming from a session variable. Using breakpoints I can see the attachments list is being populated just fine, but then when it comes to the click event handler it's empty!? Not null, just count == 0.
It becomes empty because it's not being stored in the ViewState (I'm assuming asp.net webforms here from the method names).
See How to: Save Values in View State and ASP.NET Page Life Cycle Overview
Alternatively store the value in the Session see How to: Save Values in Session State
EDIT2: with the extra info - I've had problems with this before that have been resolved by moving the code out of Page_load and into a helper method (better) and use this in the event callback. I did originally state that the event callback was coming before the Page_Load - however I've just checked this, and it doesn't, however I'm sure that I've had a problem in the past where in certain situations, with child controls, the Page_Load wasn't completing - possibly related to validation.
Anyway it should probably be recoded along the following lines - to remove the dependancy between Page_load and attachments. Using IENumerables (rather than lists) can also be neat - see the final example.
e.g.
List<Document> getAttachments()
{
List<Document> attachments = new List<Document>();
foreach(Document document in (List<Document>)Session[Request.QueryString["documentList"]])
attachments.Add(document);
}
and then in the callback:
protected void btnSend_Click(object sender, EventArgs e)
{
sendMail(getAttachments());
}
however also worth suggesting using LINQ to do it like this:
IEnumerable<Document> getAttachments()
{
return ((List<Document>)Session[Request.QueryString["documentList"]]).Select(doc => doc);
}
protected void btnSend_Click(object sender, EventArgs e)
{
sendMail(getAttachments());
// or if sendMail doesn't accept IEnumerable then do :
//sendMail(getAttachments().ToList());
}

how to write/code javascript(mouseover event) using c# methods/ c# code

note
yes client side must be java script but my qustion is not that.
i am asking that can i use c# language to implement "actions" fired on "click side events" such as mouse over
the reason for this stupid question is that i remember some syntax of registering functions for particular events of formview, which are call when the event occurs (yes there ispostback involved"
is something like the above possible for client side events using c# or even vb.net
heres a scrap of what i am trying to ask
protected void Page_Load(object sender, EventArgs e)
{
Label3.Text = "this is label three";
Label3.Attributes.Add("OnMouseOver", "testmouseover()");
}
protected void testmouseover()
{
Label4.Text = "this is label 4 mouse is working!!";
}
That is not possible.
You can use AJAX, but you cannot use AJAX to directly manipulate the DOM.
You can use an UpdatePanel, but not (easily) for mouse events.
You can use Script#, which converts C# into Javascript.
However, it would have nothing to do with server-side code
Does ClientScript.RegisterClientScriptBlock() have what you need?. Check here
You can do this by using page methods.
protected void Page_Load(object sender, EventArgs e)
{
Label3.Text = "this is label three";
Label3.Attributes.Add("OnMouseOver", "testmouseover()");
}
[webmethod]
public static void testmouseover()
{
// Implement this static method
}
and then on client side do this:
<script type='javascript'>
function testmouseover()
{
PageMethods.testmouseover();
}
</script>

Categories