dynamically create a button - c#

In Visual Studio C# windows form how do I dynamically create a button each time an item is inserted into a listbox ?
When the created button is clicked it has to remove the inserted item from the listbox.
I want to add the button th this:
if (comboBox4.Text != "" && listBox1.Text != "" && comboBox3.Text != "")
{
string ha = listBox1.SelectedItem.ToString();
Clipboard.SetText(comboBox4.Text + "stk " + ha + " i farve " + comboBox3.Text);
listBox2.Items.Add(comboBox4.Text + "stk " + listBox1.SelectedItem.ToString() +
" " + comboBox3.Text);
}

Create a button and add to the form.
Pseudo-code (not the complete solution, only the main login behind it):
public class MyEventArgs: EventArgs
{
public ListBoxValue lbv;
}
...
listBox2.Items.Add(comboBox4.Text + "stk " + listBox1.SelectedItem.ToString() + " " + comboBox3.Text);
Button x = new Button();
x.Text = "whatever";
x.Top = some coordinate;
x.Left = some coordinate;
MyEventArgs me = new MyEventArgs();
me.lbv = inserted lisbox item reference;
x.Click += new ClickHandler(this, me);
myForm.Controls.Add(x);
...
private void ClickHandler(object sender, MyEventArgs e)
{
listbox.Items.Remove(e.lbv);
}

Related

PictureBox hover over Parameter is not valid issue

I have 3 picture boxes which hold an image from a list string. There is a button which goes through each element in the list string, which in turn updates the 3 picture boxes the picture boxes that hold the 3 images are, picturebox3, 4 and 5. i have added a mouse event that triggers once the mouse is on the image to expand the image in another picturebox which is hidden until the mouse is on top of it. i created 3 extra pictureboxes which are pictureBox6, 7 and 8 to show the enlarged image which relate to picturebox3, 4 and 5. picturebox 6 is related to 3, picturebox 7 is related to 4 and 8 is related to 5.
I have tried to set the picturebox to null after the mouse is off the image however that hasn’t worked.
Below is the code for the image in picturebox 3, 4 and 5 to be updated as it goes through the list it also includes the event triggers.
download_file_names[] = the filename ".jpg"
matching_image_for_Processing[intIndex] = the folder which holds the file
Those variables above do change as i go through the list so i know that works
I have tried to set the picturebox to null after the mouse is off the image however that hasnt worked.
Below is the code for the image in picturebox 3, 4 and 5 to be updated as it goes through the list it also includes the event triggers.
if (download_file_names.ElementAtOrDefault(0) != null)
{
pictureBox3.Image = new Bitmap(Environment.CurrentDirectory + "\\" + "temp_data" + "\\" + matching_image_for_Processing[intIndex] + "\\" + download_file_names[0]);
pictureBox3.MouseHover += new EventHandler((sender2, e2) => pictureBox3_Mouse(sender2, e2, download_file_names[0], matching_image_for_Processing[intIndex]));
pictureBox3.MouseLeave += new EventHandler(pictureBox3_MouseLeave);
}
else
{
pictureBox3.Image = new Bitmap(Environment.CurrentDirectory + "\\" + "NoImage.bmp");
}
if (download_file_names.ElementAtOrDefault(1) != null)
{
pictureBox4.Image = new Bitmap(Environment.CurrentDirectory + "\\" + "temp_data" + "\\" + matching_image_for_Processing[intIndex] + "\\" + download_file_names[1]);
pictureBox4.MouseHover += new EventHandler((sender2, e2) => pictureBox4_Mouse(sender2, e2, download_file_names[1], matching_image_for_Processing[intIndex]));
pictureBox4.MouseLeave += new EventHandler(pictureBox4_MouseLeave);
}
else
{
pictureBox4.Image = new Bitmap(Environment.CurrentDirectory + "\\" + "NoImage.bmp");
}
if (download_file_names.ElementAtOrDefault(2) != null)
{
pictureBox5.Image = new Bitmap(Environment.CurrentDirectory + "\\" + "temp_data" + "\\" + matching_image_for_Processing[intIndex] + "\\" + download_file_names[2]);
pictureBox5.MouseHover += new EventHandler((sender2, e2) => pictureBox5_Mouse(sender2, e2, download_file_names[2], matching_image_for_Processing[intIndex]));
pictureBox5.MouseLeave += new EventHandler(pictureBox5_MouseLeave);
}
else
{
pictureBox5.Image = new Bitmap(Environment.CurrentDirectory + "\\" + "NoImage.bmp");
}
below is the code for the other picturesboxes to display the larger image.
void pictureBox3_Mouse(object sender, EventArgs e, string catching, string catching2)
{
pictureBox6.Visible = true;
pictureBox6.Image = new Bitmap(Environment.CurrentDirectory + "\\" + "temp_data" + "\\" + catching2 + "\\" + catching);
Console.WriteLine("temp_data" + "\\" + catching2 + "\\" + catching);
pictureBox6.Refresh();
}
void pictureBox3_MouseLeave(object sender, EventArgs e)
{
pictureBox6.Visible = false;
pictureBox6.Image = null;
pictureBox6.Refresh();
}
void pictureBox4_Mouse(object sender, EventArgs e, string catching_1, string catching2_1)
{
pictureBox7.Visible = true;
pictureBox7.Image = new Bitmap(Environment.CurrentDirectory + "\\" + "temp_data" + "\\" + catching2_1 + "\\" + catching_1);
pictureBox7.Refresh();
}
void pictureBox4_MouseLeave(object sender, EventArgs e)
{
pictureBox7.Visible = false;
pictureBox7.Image = null;
pictureBox7.Refresh();
}
void pictureBox5_Mouse(object sender, EventArgs e, string catching_2, string catching2_2)
{
pictureBox8.Visible = true;
pictureBox8.Image = new Bitmap(Environment.CurrentDirectory + "\\" + "temp_data" + "\\" + catching2_2 + "\\" + catching_2);
pictureBox8.Refresh();
}
void pictureBox5_MouseLeave(object sender, EventArgs e)
{
pictureBox8.Visible = false;
pictureBox8.Image = null;
pictureBox8.Refresh();
}
I am hoping someone can help me solve this issue, as i go to the next element in the list and hover over the new image i keep getting the error Parameter is not valid. i believe the picturebox is holding the previous variable.

in C#, Append selection multiple times from 2 ComboBoxes into a TextBox using a button

I am trying to append selections from 2 ComboBoxes into a TextBox with a click of a button and I am not sure how to do this. I can do it once with code like this:
private void BTN_APPEND_Click(object sender, EventArgs e)
{
TB_CONNECTORS.Text = CB_PORT_NUMBER.Text + " " + CB_CONNECTOR.Text;
}
And this will result in
Append with the click of a button
but the question is, how can I append to this one more time?
Did you try this :
if(!TB_CONNECTORS.Text == "")
{
TB_CONNECTORS.Text = TB_CONNECTORS.Text + " & " + CB_PORT_NUMBER.Text + " " + CB_CONNECTOR.Text;
}
else
{
TB_CONNECTORS.Text = CB_PORT_NUMBER.Text + " " + CB_CONNECTOR.Text;
}
This will result in the new value achieved from the 2 comboboxes keeping the existing text of the textbox

Close Current form open new one of that form closed

i have 2 form
in form 1 i have a button when i click on button form 2 will be show and my data are showing on form 2 so far its OK
but i want when one of form 2 its open if user click on button in form 1 then close this form 2 and open a new one! not open an other form 2
i hope u understand my question :D sorry for bad English
i tried form instance function but its not working its just hold this form 2 and will not allow to open new one!
with these code:
public static Form2 Instance
{
get
{
if (_form2 == null)
{
_form2 = new Form2();
}
return _form2;
}
}
and here is button code :
private void btnSave_Click(object sender, EventArgs e)
{
if (RadioMale.Checked == true)
{
jensiyat = "مرد";
}
else { jensiyat = "زن"; }
if (RadioMarried.Checked == true)
tahol = "متاهل";
else tahol = "مجرد";
Class1.txt +=
"________________________\n\n" + "مشخصات مربوط به خانم/آقای "
+ tbFamily.Text + "\n________________________" +
"\nنام و نام خانوادگی: " + tbName.Text + " " +
tbFamily.Text + "\n" + "ایمیل: " + tbEmail.Text + "\n" + "شماره ملی: " +
tbCodmeli.Text + "\n" + "سریال شناسنامه: " +
tbSerialShenasname.Text
+ "\nشهر محل زندگی: "+ shahr + " - " + TreeShahr.SelectedNode.Text
+ "\nآدرس: " + tbAddress.Text + "\n"
+ " تحصیلات : " + ComboTahsilat.SelectedItem
+ "\nجنسیت : " +jensiyat
+ "\nوضعیت تاهل: " + tahol
+ "\nتاریخ تولد: " + BirthTimePicker.Value.ToPeString()
+ "\n__________________________________________________";
Form frm2 = new Form2();
frm2.Show();
}
You can use Application.OpenForms. Gets a collection of open forms owned by the application.
List<Form> forms = new List<Form>();
// All opened myForm instances
foreach(Form f in Application.OpenForms){
if (f.Name == "Form2"){
f.Close();
break;
}
}
You can Show form like
Form2 ff = new Form2();
ff.Show();
Declare the Variable for the Form2 as class variable outside of the scope of the btnSave_Click method. This way you will be able to access it again when the button is clicked a second time.
Form frm2 = new Form2();
private void btnSave_Click(object sender, EventArgs e)
{
if(frm.Visible) // check whether the form is already showing
{
frm.Close(); // if yes close it first
}
frm2 = new Form2(); // then make a new form and show it
frm2.Show();

Creating a statusfield for users

I need some guidance here on why this isn't working:
So here's the issue, I want to give my users a little status field so they can check how long it will take and get a coffee or two for them.
My Problem is that the statusfield (2 Labels), are not updated during the process.
This is my current code :
private void Cancel_Click(object sender, EventArgs e)
{
this.Close();
}
private void start_change_Click(object sender, EventArgs e)
{
DialogResult dr = MessageBox.Show("Start process?", "DateChanger", MessageBoxButtons.OKCancel, MessageBoxIcon.Hand);
if (dr == DialogResult.OK)
{
//get files
List<String> d = new List<String>();
label_status_title.Text = "Status: collecting Data, take a coffee while waiting.\nfiles changed: 0 files";
d = getFiles("H:\\");
int i = 0;
double diff = 0.0;
//modify files
label_status_title.Text = "Status: changing files.\nfiles changed: 0/" + d.Count + " files.";
foreach (String s in d)
{
String label = "\nfile: " + s;
//create newDate and modify creation and lastwrite
DateTime actualDate = Directory.GetLastWriteTime(s).Date;
DateTime newDate = new DateTime(2015, 03, 01);
diff = (newDate - actualDate).TotalDays;
label += "\nactual creation date: " + Directory.GetCreationTime(s).Date;
label += "\nnew creation date: " + newDate.Date;
label += "\nactual last write date: " + Directory.GetLastWriteTime(s).Date;
label += "\nnew last write date: " + newDate.Date;
if (diff > 400)
{
try
{
//set new timevalues
Directory.SetCreationTime(s, newDate);
Directory.SetCreationTimeUtc(s, newDate);
Directory.SetLastWriteTime(s, newDate);
Directory.SetLastWriteTimeUtc(s, newDate);
}
catch (UnauthorizedAccessException UAE)
{
}
i++;
label += "\nchange needed.";
}
else
{
label += "\nchange not needed.";
}
label_status.Text = label;
label_status_title.Text = "Status: changing files.\nfiles changed: " + i + "/" + d.Count + " files.";
}
MessageBox.Show("Process finished, changed: " + i + "/" + d.Count + " files.");
}
}
private List<String> getFiles(string sDir)
{
List<String> files = new List<String>();
try
{
foreach (string f in Directory.GetFiles(sDir))
{
files.Add(f);
}
foreach (string d in Directory.GetDirectories(sDir))
{
files.AddRange(getFiles(d));
}
}
catch (System.Exception excpt)
{
MessageBox.Show(excpt.Message);
}
return files;
}
private void DateChanger_Load(object sender, EventArgs e)
{
String label = "";
label_status_title.Text = "Status: \nfiles changed: 0 files";
label += "file: ";
label += "\nactual creation date: ";
label += "\nnew creation date: ";
label += "\nactual last write date: ";
label += "\nnew crealast writetion date: ";
label_status.Text = label;
}
I also tried the suggestion of using MethodInvoker, but that also didn't work either. Any guidance or suggestions here are appreciated.
Thanks.
Mirko
p.s. if there is a better solution than using labels or text boxes for this feel free to tell me. :)
Youre Method start_change_Click(object sender, EventArgs e) is blocking the main thread. To avoid this, use a separate thread to update the labels.
Check out this post: Thread freezes main UI
Just refresh the Label after assigning it a new Text value.
label_status_title.Text = "Status: changing files.\nfiles changed: " + i + "/" + d.Count + " files.";
label_status_title.Refresh(); //added

how to maintain scroll position on postback in Gridview / Repeater

I have a Repeater and when number of data increases the scroll bar is diaplayed.
when i click on any row inside repeater it gets selected and it displays the data correspondingly in next div.
suppose i click on the last record, the data is displayed and row is also highlighted but the scroll goes to its initial position and not last.
Simply put in the following in Page_Load:
this.Page.MaintainScrollPositionOnPostBack = True
Page.MaintainScrollPositionOnPostBack Property
protected void Page_Load(object sender, EventArgs e) { ScrolBar();}
private void ScrolBar()
{
HiddenField PosX = new HiddenField();
HiddenField PosY = new HiddenField();
HtmlControl Form1 = this.Master.FindControl("Form1") as HtmlControl;
PosX.ID = "PosX";
PosY.ID = "PosY";
Form1.Controls.Add(PosX);
Form1.Controls.Add(PosY);
string script;
script = "window.document.getElementById('" + PosX.ClientID + "').value = "
+ "window.document.getElementById('" + test1.ClientID + "').scrollLeft;"
+ "window.document.getElementById('" + PosY.ClientID + "').value = "
+ "window.document.getElementById('" + test1.ClientID + "').scrollTop;";
this.ClientScript.RegisterOnSubmitStatement(this.GetType(), "SavePanelScroll", script);
if (IsPostBack)
{
script = "window.document.getElementById('" + test1.ClientID + "').scrollLeft = "
+ "window.document.getElementById('" + PosX.ClientID + "').value;"
+ "window.document.getElementById('" + test1.ClientID + "').scrollTop = "
+ "window.document.getElementById('" + PosY.ClientID + "').value;";
this.ClientScript.RegisterStartupScript(this.GetType(), "SetPanelScroll", script, true);
}
}
For Repeater or GridView try this:
Put control inside div and add an option OnSorting
<div id="divGridView" runat="server" >
<asp:GridView ID="Grid" runat="server" OnSorting="Grid_OnSorting"
OnDataBound="Grid_DataBound" >
on code file add this method:
protected void Grid_OnSorting(object sender, EventArgs e)
{
divGridView.Page.SetFocus(Grid);
}
You can use below link using jquery
http://www.sergeyakopov.com/2010/11/easily-maintaining-scroll-position-in-gridview-using-jquery

Categories