Unable to create multiple Controls on Button Click Event - c#

I'm trying to create a asp:UploadFile control dynamically on button click event. After creating the first control it won't create a second or third one. Below is my code.
protected void AddFileInputControl_Click(object sender, EventArgs e)
{
FileUpload image = new FileUpload();
image.ID = "image";
fileinputs_div.Controls.Add(image);
}
Any help will be greatly appreciated.

Try to give unique ID for each image, for example using global counter :
private int counter;
protected void AddFileInputControl_Click(object sender, EventArgs e)
{
FileUpload image = new FileUpload();
image.ID = "image" + counter++;
fileinputs_div.Controls.Add(image);
}

Asp.net doesn't save the dynamically created control for the next calls. That means you would need to create them every PostBack. Something like this:
private int _counter = 0
protected void AddFileInputControl_Click(object sender, EventArgs e)
{
for (int i = 0; i < _counter; i++)
{
fileinputs_div.Controls.Add(new FileUpload()
{
ID = string.Format("image #{0}", i);
});
}
_counter++;
}

Related

get name for dynamic created labels with a existing button on the form

I am creating a Label dynamiclly on my windows form like this:
for (int i = 0; i < 3; i++)
{
tableLayoutPanel1.Controls.Add(new Label() {
Text = dr["name"].ToString(),
Name = string.Format("test_{0}", i)
}, 1, i);
}
now what I have Button in my form when I click on it I want it to display the Text in the Label:
private void button3_Click(object sender, EventArgs e)
{
MessageBox.Show(test_1.Text); // <- Compile time error here
}
but it says test_1 does not exist.
Which I understand why since its dynamically made; but is it possible for me to achieve this?
In case of runtime created Control (Label in your case) you have to find it. You can do it with a pinch of Linq:
using System.Linq;
...
private void button3_Click(object sender, EventArgs e)
{
Label testLabel = tableLayoutPanel1
.Controls
.Find("test_1", true)
.OfType<Label>()
.FirstOrDefault();
MessageBox.Show(testLabel?.Text ?? "Label not found");
}

Init HalconWindow/HSmartWindowControlWPF in Background in C#

Is there any way to initialize a HalconWindow or a HSmartWindowControlWPF in C#?
I am having multiple HSmartWindowControlWPFs in a TabView but only those that were visible before are updated. So if I am trying to put an HImage in all HalconWindows, without choosing another Tab than the default before, only the default Tab gets updated, all other HalconWindows stay black. But if they were once selected they are updated.
Is there any way to create this behaviour automatically?
The key is to index through the tabs at initialization so that they initialize the controls.
private void TabbedHalconApp_Loaded(Object sender, RoutedEventArgs e)
{
TabControl1.BeginInit();
for (int index = 0; index < this.TabControl1.Items.Count; index++)
{
this.TabControl1.SelectedIndex = index;
this.TabControl1.UpdateLayout();
}
// Reset to first tab
this.TabControl1.SelectedIndex = 0;
TabControl1.EndInit();
}
Then you can load the image to the Halcon window. Here is how you might do this when the form is loaded.
private void HWindow2_Loaded(Object sender, EventArgs e)
{
(sender as HSmartWindowControlWPF).HalconWindow.DispImage(myTestImage);
}
private void HWindow1_Loaded(Object sender, RoutedEventArgs e)
{
(sender as HSmartWindowControlWPF).HalconWindow.DispImage(myTestImage);
}

Timer keep reloading the page in c# [duplicate]

I want to increase values on timer tick event but it is not increasing don't know what I am forgetting it is showing only 1.
<asp:Timer ID="Timer1" runat="server" OnTick="Timer1_Tick" Interval="1000"></asp:Timer>
private int i = 0;
protected void Timer1_Tick(object sender, EventArgs e)
{
i++;
Label3.Text = i.ToString();
}
You can use ViewState to store and then read the value of i again.
int i = 0;
protected void Timer1_Tick(object sender, EventArgs e)
{
//check if the viewstate with the value exists
if (ViewState["timerValue"] != null)
{
//cast the viewstate back to an int
i = (int)ViewState["timerValue"];
}
i++;
Label3.Text = i.ToString();
//store the value in the viewstate
ViewState["timerValue"] = i;
}
Check whether the form is posted back and then assign values. Check IsPostBack
private int i;
protected void Timer1_Tick(object sender, EventArgs e)
{
if (!IsPostBack)
{
i = 0;
}
else
{
i = Int32.Parse(Label3.Text);
i++;
}
Label3.Text = i.ToString();
}
Generally speaking it is not a good practice to store values inside of views (such as asp.net page). It could be overwritten each time the request is sent.
You could store your data elsewhere:
public static class StaticDataStorage
{
public static int Counter = 0;
}
And use it:
protected void Timer1_Tick(object sender, EventArgs e)
{
StaticDataStorage.Counter++;
Label3.Text = StaticDataStorage.Counter.ToString();
}

How to use dynamic button click event handler without using page init or page load

I am trying to figure out how to use a click event handler for my 4 buttons that I have generated dynamically without putting any code in page init or oninit. I have one button that once clicked it generates 4 more buttons. The click event handler for these 4 buttons is not working. Here is the code. Has anybody figured out a way to use the click events in asp.net c# without first putting it in page_load? If I can solve this problem, I can solve my real problem in a bigger scenario.:
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < 4; i++)
{
Button b = new Button();
b.ID = i.ToString();
b.Text = "ClickMe";
b.Visible = true;
b.Click += new EventHandler(b_click);
PlaceHolder1.Controls.Add(b);
}
}
void b_click(object sender,EventArgs e)
{
Label1.Text = "ok";
}
Make sure the ID of your dynamic controls include a distinct keyword. In my example below I prepended "DYNAMIC_" to their ID. Then override OnPreRender() like this:
protected override void OnPreRender(EventArgs e)
{
if (Page.IsPostBack && !IsPostBackEventControlRegistered)
{
var controlName = this.Request.Form.AllKeys.SingleOrDefault(key => key.Contains("DYNAMIC_"));
processEventForDynamicControl(controlName);
}
base.OnPreRender(e);
}
private void processEventForDynamicControl(string controlName)
{
//Do your dynamic button click processing here
}
Of course, if your dynamic controls use doPost() (which sadly Button doesn't) you can retrieve the control directly from __EVENTTARGET like this:
var controlName = Request.Params.Get("__EVENTTARGET")
You want to load controls inside Page_Load. Otherwise, they are not in control tree, and they won't be able to trigger b_click event.
public int Counter
{
get { return (int?) ViewState["Counter"] ?? 0; }
set { ViewState["Counter"] = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
var counter = Counter;
for (int i = 0; i < counter; i++)
{
Button b = new Button();
b.ID = i.ToString();
b.Text = "ClickMe";
b.Visible = true;
b.Click += b_click;
PlaceHolder1.Controls.Add(b);
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Counter = 4;
for (int i = 0; i < 4; i++)
{
Button b = new Button();
b.ID = i.ToString();
b.Text = "ClickMe";
b.Visible = true;
b.Click += b_click;
PlaceHolder1.Controls.Add(b);
}
}
void b_click(object sender, EventArgs e)
{
Label1.Text = "ok";
}
Note: If you plan to load inside Page_Init, you want to use Session instead of ViewState.
Basically I got it working.There is no way around it. You have to use Oninit or Page_load and put your b.Click += new EventHandler(b_click) code there in addition to the PlaceHolder1.Controls.Add(b); there as well,for the event handler to register properly with the button. The problem with this method is that it places the button on top of the PlaceHolder portion of the web page which is not what I want. I want to beable to place the button at a particular position in the web page. So how do you go around doing this? Basically after the PlaceHolder1.Controls.Add(b) simply make the button invisible. Then in the when you are ready to place the button in a particular part of your html call PlaceHolder1.Controls.Add(b) again and make it visible. That works for me. If anyone needs help with this I can post some sample code and you can test it for yourself. Thanks all.

Increment number every time button is click

I want to increase an int variable i whenever I click on a button. But what I get is only int value of 1 and it doesn't increase anymore.
Here is my code:
private int i;
protected void btnStart_Click(object sender, EventArgs e)
{
i++;
lblStart.Text = i.ToString();
}
By each request (Clicking on the button), a new instance will be created.
So your non-static variable will be reset to 0.
You can define i as static:
private static int i;
protected void btnStart_Click(object sender, EventArgs e)
{
i++;
lblStart.Text = i.ToString();
}
But please note that the i variable is shared between all the users.
To improve this issue, you can use Session.
Session is an ability to store data of each user in a session.
So you can use following property to change the i variable in each session:
private int i
{
get
{
if (Session["i"] == null)
return 0;
return (int)Session["i"];
// Instead of 3 lines in the above, you can use this one too as a short form.
// return (int?) Session["i"] ?? 0;
}
set
{
Session["i"] = value;
}
}
protected void btnStart_Click(object sender, EventArgs e)
{
i++;
lblStart.Text = i.ToString();
}
As you know other answer is correct i want add another answer
You must in webform save your variables in ViewState
Just define your variables like this
public int i
{
get { Convert.ToInt32( ViewState["i"] ); }
set { ViewState["i"] = value ; }
}
Convert lblStart.Text value to int every time and assign it to i. Then increase i.
private int i;
protected void btnStart_Click(object sender, EventArgs e)
{
i = Int32.Parse(lblStart.Text);
i++;
lblStart.Text = i.ToString();
}
I have similar questions as yours and I believe the issue is because the event click did not store the value that has been increased before, therefore it could not be incremented the next time you clicked, so here's my code:
protected void btn_add_Click(object sender, EventArgs e)
{
string initial;
int increment;
int quantity;
initial = TextBoxQty.Text;
increment = Convert.ToInt16(initial);
increment++;
TextBoxQty.Text = increment.ToString();
quantity = increment;
}
You can use a hidden field, initialize them to 0.
private int i;
protected void btnStart_Click(object sender, EventArgs e)
{
i = int.Parse(myHiddenField.Value);
i++;
myHiddenField.Value = i;
lblStart.Text = i.ToString();
}
protected static int a = 0;
protected void btnStart_Click(object sender, EventArgs e)
{
a = a+1;
lblStart.Text = i.ToString();
}
It Works for me but on page_load() it initiates the value from 1 again !
this is actually my first time doing this
int i = 0;
while (i>=0)
{
Console.WriteLine(i);
Console.ReadLine();
i++;
}

Categories