C# syntax to get access to webcontrol in different file (aspx) - c#

Within my Website project, I have some aspx pages, javascript files, and a custom C# class I called MyCustomReport. I placed a Image box with an ID of Image1 inside SelectionReport.aspx. I need to get access to that Image1 inside MyCustomReport.cs so I can turn it on and off based on conditions. What code do I need to do this? Thanks everyone

You'll need to pass the instance of Image control to MyCustomReport. From there you'll be able to set it's Visible property to true or false.
Probably something like this
public partial class SelectionReport : Page
{
// your code here
protected void Page_Load( object sender, EventArgs e ){
MyCustomReport myCustomReport = new MyCustomReport();
myCustomReport.MyReport( Image1 );
}
}
public class MyCustomReport
{
public void MyReport( Image arg ){
// some more code
arg.Visible = false; // or true
}
}
EDIT derek is right, you won't need the entire page, just the image.

it sounds a bit odd to do it that way. You could pass the control to the class method using the ref keyword, then the class could modify it:
doSomething(data, MyUserControl);
I think a better implementation would be for your class to have a method or property that the page could query to turn the control on or off.

Related

How to modify control properties through variable reference

I've been working on making a project of mine more modular. Something I've wanted to do is have multiple buttons use the same function when they perform a similar action, but with different values. I've been stuck on trying to apply this to the following situation:
"When this button is clicked, have the user select an image, and then have a PictureBox display the selected image". Each button has its own PictureBox. All Controls have been created before runtime.
Hope that makes sense!
My last attempt can be seen in the code below- I have tried assigning the Controls(Button and PictureBox) to variables to be stored together in a class. There's 6 of these classes all included within a single List.
I've also tried to store only the Control Names and then using this.Controls.Find to retrieve the Controls.
I've tried quite a few smaller changes such as passing by reference, making the List static, and things such as that would (somehow)magically do the trick- I've gotten desperate.
public class score_control
{
public Button score_button;
public PictureBox score_picture;
public int picture_index;
}
public List<string> score_boxes_names = new List<string>();
public List<score_control> score_boxes = new List<score_control>();
public void add_score_control(Button button, PictureBox pictureBox)
{
score_control new_score = new score_control();
new_score.score_button = button;
new_score.score_picture = pictureBox;
new_score.picture_index = score_boxes.Count();
score_boxes.Add(new_score);
score_boxes_names.Add(button.Name);
}
public score_control find_score_control(string name)
{
int index = score_boxes_names.IndexOf(name);
return score_boxes[index];
}
public frm_settings()
{
InitializeComponent();
add_score_control(btn_score1_image1, pic_score1_image1);
add_score_control(btn_score1_image2, pic_score1_image2);
add_score_control(btn_score1_image3, pic_score1_image3);
add_score_control(btn_score2_image1, pic_score2_image1);
add_score_control(btn_score2_image2, pic_score2_image2);
add_score_control(btn_score2_image3, pic_score2_image3);
}
private void score_button_Click(object sender, EventArgs e)
{
Button image_button = (Button)sender;
if (ofd_png.ShowDialog() == DialogResult.OK)
{
score_control clicked_control = find_score_control(image_button.Name);
score_image[clicked_control.picture_index] = ofd_png.FileName;
clicked_control.score_picture.Image = Image.FromFile(ofd_png.FileName);
}
}
The problem seems centered around this line:
clicked_control.score_picture.Image = Image.FromFile(ofd_png.FileName);
The program throws a NullReferenceException , but clickedcontrol is being recognized in the Local Watch, as well as score_image being noted to be a PictureBox(as it should be).
When I instead held the Control Names in the class, I had broke this line down into multiple lines, but the following line produced a NullReferenceException:
Control[] find_control = this.Controls.Find(clicked_control.score_picture, true);
In this case, clicked_control.score_picture would be a string containing the PictureBox Name. Again, the Local Watch showed that it clicked_control was not null, and neither was score_picture.
Any help figuring out how to properly store a Control within a variable to later be used to modify that Control's properties would be greatly appreciated.
dontpanic was able to help me out with this one. The issue was actually outside of this code - it had to do with the line score_image[clicked_control.picture_index] = ofd_png.FileName;. The way score_image was initialized as an array was incorrect. Fixing that made everything work fine.

Xamarin Forms: MasterPage Helper class

My current app has multiple master detail pages. I want to create a helper class which has a function that accepts list of PageModels-Pages( ViewModels-views ) which I can iterate through and create master detail pages.
MyCurrent Code:
public static Page SetupMasterDetailNav<T,U>( Dictionary<T,string> Menu)
where T : class
//In Dictionary T is ViewModel(PageModel) ,
String is name displayed on Master page
{
var masterDetail = new FreshMasterDetailNavigationContainer();
foreach (KeyValuePair<T,string> item in Menu)
{
masterDetail.AddPage<item.Key>(item.Value);
}
masterDetail.Init("");
return masterDetail;
}
This code doesn't work.It tells me item.key is a variable and cannot be used as a type Can any one suggest me a better approach or how else I can achieve my goal ?
The AddPage<T> method is a generic method, which expects a type. In this case it is FreshBasePageModel. The normal usage would be something like:
masterDetail.AddPage<MyViewModel>("MyPage", model);
or:
masterDetail.AddPage<MyViewModel>("MyPage");
Since your method is already generic, and seems you want it to be the type of the ViewModel you could simply do:
masterDetail.AddPage<T>(item.Value);
To do this you must change the your method signature to something like:
public static Page SetupMasterDetailNav<T,U>(Dictionary<T,string> Menu)
where T : FreshBasePageModel
Not sure what the U is used for in your case, you haven't shown usage of it.
Why are you even doing this is puzzling me.

Custom WinForms button does not change image?

I created a custom Button, called AcceptButton, inheriting from System.Windows.Forms.Button
On the constructor I set a few properties, but most important, an image (A green checkmark), like this:
this.Image = Proyecto.Controls.Bases.Properties.Resources.ok_16;
When I add this control using VS2013 form designer, in another project that references the DLL I just created, the image is displayed correctly. But if I go into my control, and change the image in code, for example, to:
this.Image = Proyecto.Controls.Bases.Properties.Resources.ok_32;
The image is not changed in the projects that use this control (even if the solution is cleaned and regenerated). I followed the code generated by VS2013 and I found that the designer adds this line:
this.botonAceptar1.Image = ((System.Drawing.Image)(resources.GetObject("botonAceptar1.Image")));
For some reason, this resource is "hardcoded" in a resource file generated by VS, but it's not updated when I regenerate the solution.
Removing this line makes it work as expected (I can change the image in the "upstream" class and it'll be updated when the solution is regenerated).
Why is this happening?
How can I avoid this?
This happens due to the DesignerSerializationVisibility (MSDN) attribute. Try adding this property and these methods (MSDN) to your class:
public class MyButton : System.Windows.Forms.Button
{
public bool ShouldSerializeImage()
{
return !object.ReferenceEquals(this.Image, _BaseImage);
}
public void ResetImage()
{
this.Image = _BaseImage;
}
[System.ComponentModel.DesignerSerializationVisibility(System.ComponentModel.DesignerSerializationVisibility.Visible)]
public new Image Image
{
get { return base.Image; }
set { base.Image = value; }
}
private Bitmap _BaseImage;
public MyButton()
{
_BaseImage = Proyecto.Controls.Bases.Properties.Resources.ok_16;
this.Image = _BaseImage;
}
}
This replaces the default Image property and prevents the serialization you encountered. Furthermore it allows the designer to check if the property has it's default value and if it needs to be serialized. The default value is stored in a private field in the button class. This should correctly serialize (or not serialize) the properties.
Remove all buttons you have, recompile, readd the buttons to make sure.

Passing a parameter to a programmatically created User Control

Let me just preface this with: I Googled high and low for this, and found many examples and solutions, and I still can't figure this out.
In a .aspx.cs code behind file, I have the following:
NewsArticleList listall = NewsArticleManager.GetListAll();
foreach (NewsArticle x in listall)
{
Control c1 = (NewsArticleContainer)LoadControl("~/UserControls/NewsArticleContainer.ascx");
((NewsArticleContainer)c1).PopulateWithNewsArticle(x);
mynewspanel.Controls.Add(c1);
}
I have a method in the User Control called PopulateWithNewsArticle() that accepts a NewsArticle, and populates the User Control's web controls accordingly:
public void PopulateWithNewsArticles(NewsArticle x)
{
lbltitle.Text = x.Title;
lblcategory.Text = x.Category;
//...etc.
}
Now this works, this is fine. But what I would like to learn/understand, is how I can pass the NewsArticle x to the User Control when I LoadControl(), so that upon creation of the User Control, I can unpackage the NewsArticle on the User Control's Page_Load, and set the web control properties from right when the User Control is instantiated as opposed to doing it after instantiation with the PopulateWithNewsArticle method (like I have it now).
Our you can expose public property NewsArticle in the NewsArticleContainer.ascx, so you will have initialization code like this:
var control = (NewsArticleContainer)LoadControl("~/UserControls/NewsArticleContainer.ascx");
control.NewsArticle = x;
You could use
Control c1 =
(NewsArticleContainer)LoadControl(typeof(NewsArticleContainer),new object[]{ x });
This one is an overloaded of Page.LoadControl(), It has this syntax
public Control LoadControl(
Type t,
Object[] parameters
)
After that you would have to create a valid constructor for your UserControl too, which could be something like this
class NewsArticleContainer:System.Web.UI.UserControl
{
public NewsArticleContainer(NewsArticle x)
{
// Some cool code stuff here
}
}
For more on this go here.

Listbox not showing items

I want my items list in a listbox but when i try
listbox1.Items.Add("Item1");
nothing is being added but
if i place the code in the forms load metod it works but when I call it from the
separate code module it does not. I think this is because another instance
of the form is being updated.
but how do i get the active form and then add the items.
I got a Abstract class and tree subclasses and i want my subclasses in a list and then showed on the form.
this was my first attempt but this dosent work.
private void button1_Click(object sender, EventArgs e)
{
Subclass o = new Subclass();
List<BaseClass> l = new List<BaseClass>();
l.Add(o);
Form1 f = new Form1();
f.AddObjectToListbox(l);
}
And then in my From1 i got
public void AddObjectToListbox(List<BaseClass> l)
{
foreach (Subclass objectname in l.OfType<Subclass>())
{
l.Items.Insert(0, "text" + O.getMetod);
}
}
but like it is now it just add to another instance of form1.
thanks for alle the help.
Your question is a litle bit vague...where are you calling listbox1.Items.Add("Item1"); from
e.g.
From a method in the Forms class file
From code in another file,
From code in a different assembly,
However, you can get the Active Form via the Form class static method:
System.Windows.Forms.Form.ActiveForm
May this helps
One problem might be the use of "Object" as both a class and variable name in the AddObjectToListBox method.
Also if you are casting obj to Subclass, but then assign it to a variable of type Object, that is not making much sense. You could solve both of these at once, like this.
foreach (Subclass obj in l.OfType<Subclass>())
{
lbVehicles.Items.Insert(0, "text" + obj.getMetod);
}
As a third, it looks like you're creating a new form every time the button is clicked, is that intentional?
suddenly you find what you was looking for yourself.
this did it.
Form currentForm = Form.ActiveForm;
ListBox lb = (ListBox)currentForm.Controls.Find("ListboxName", true)[0];
but still thanks for looking at my question.
First try to clear items and then try to add

Categories