Calling variable from another event - c#

I want to call a variable from another event, for example
public void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
var ccc = lblTicketsA;
}
public void btnSubmit_Click(object sender, EventArgs e)
{
try
{
ccc.text = "test";
}
catch (Exception ex)
{
lblDisplay.Text = ex.Message;
}
}
thank you

Make ccc an instance field like this:
private SomeType ccc;
public void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
this.ccc = lblTicketsA;
}
public void btnSubmit_Click(object sender, EventArgs e)
{
try
{
this.ccc.text = "test"
}
catch (Exception ex)
{
lblDisplay.Text = ex.Message;
}
}

Related

C# can't use variable from IF statement

I'm making easy password generator, but i cant pick int from try and string from if. Here's the code. I hope you help me. I cant make this I as textbox and i cant do nothing with it.
private void button3_Click(object sender, EventArgs e)
{
try
{
int i = Int32.Parse(textBox2.Text);
return;
}
catch
{
}
CreatePassword(i);
}
and here is part of CreatePassword function
public string CreatePassword(int length)
{
if (checkBox2.Checked)
{
const string src = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
return src;
}
else
{
const string src = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
return src;
}
}
There are several problems with your code. First, you're trying to access the variable i outside of the scope in which it is declared; it's not visible outside of the try statement. Second, it seems like you're expecting the password to be generated from the integer you parsed, but you're explicitly returning before the password can be created. Thirdly, you're not doing anything with the created password, just throwing it away.
Try the following:
private void button3_Click(object sender, EventArgs e)
{
try
{
int i = Int32.Parse(textBox2.Text);
string password = CreatePassword(i);
// TODO: use the 'password' string for something.
return;
}
catch
{
}
}
You should also consider using int.TryParse instead, which won't throw an exception.
if (int.TryParse(textbox2.Text, out int i) {
string password = CreatePassword(i);
// Do something with 'password'
} else {
// Display an error.
}
From your example, it looks like all your need is Int32.TryParse:
int.TryParse(textBox2.Text, out int i);
CreatePassword(i);
However, to answer your original question: you need to initialize i variable outside of the try block in order to be able to use it after it. For instance:
int i = 0;
try
{
i = int.Parse("test");
}
catch
{
}
Console.WriteLine(i); // 0
You logic is a bit flawed. If Textbox2 does not contain a valid integer, you ignore the exception and just create a password. What kind of password you expect to create?
I think you mean to do something like this:
private void button3_Click(object sender, EventArgs e)
{
try
{
int i = Int32.Parse(textBox2.Text);
CreatePassword(i);
}
catch
{
// Show a messagebox or something
}
}
Guys all thanks for help. I did it. Here you have my source of my application as thanks for you all. My app completely work and i believe you understand my logic :D
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Password_generator
{
public partial class Form1 : Form
{
private bool _dragging = false;
private Point _start_point = new Point(0, 0);
public Form1()
{
InitializeComponent();
}
public string CreatePassword(int length)
{
string src;
var sb = new StringBuilder();
Random RNG = new Random();
src = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
if (checkBox2.Checked)
{
src += "1234567890";
}
if (checkBox3.Checked)
{
src += "##$%^&*()";
}
for (var i = 0; i < length; i++)
{
var c = src[RNG.Next(0, src.Length)];
sb.Append(c);
}
textBox1.Text = sb.ToString();
if (checkBox1.Checked)
{
try
{
File.AppendAllText("hesla.txt", textBox1.Text + Environment.NewLine);
}
catch(Exception o)
{
MessageBox.Show("Něco se nepovedlo! " + Environment.NewLine + "(" + o.Message + ")");
}
}
return textBox1.Text;
}
private void button3_Click(object sender, EventArgs e)
{
try
{
int i = Int32.Parse(textBox2.Text);
CreatePassword(i);
}
catch
{
MessageBox.Show("Musíš zadat číslo!");
}
}
private void button1_Click(object sender, EventArgs e)
{
this.Close();
}
private void button2_Click(object sender, EventArgs e)
{
this.WindowState = FormWindowState.Minimized;
}
private void panel1_MouseUp(object sender, MouseEventArgs e)
{
_dragging = false;
}
private void panel1_MouseMove(object sender, MouseEventArgs e)
{
if (_dragging)
{
Point p = PointToScreen(e.Location);
Location = new Point(p.X - this._start_point.X, p.Y - this._start_point.Y);
}
}
private void panel1_MouseDown(object sender, MouseEventArgs e)
{
_dragging = true;
_start_point = new Point(e.X, e.Y);
}
private void panel3_Paint(object sender, PaintEventArgs e)
{
}
private void checkBox3_CheckedChanged(object sender, EventArgs e)
{
}
private void checkBox2_CheckedChanged(object sender, EventArgs e)
{
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void label3_Click(object sender, EventArgs e)
{
}
private void label1_Click(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button4_Click(object sender, EventArgs e)
{
try
{
Clipboard.SetText(textBox1.Text);
}
catch
{
}
}
}
}

AxMsRdpClient8NotSafeForScripting.Connect() not working No Exceptions, Not Errors

I'm trying to check my RDP credentials using c#
Here is my reference : Remote Desktop using C#.NET
And here is what I've done so far :
private void testBtn_Click(object sender, EventArgs e) {
try {
AxMsRdpClient8NotSafeForScripting ax = new AxMsRdpClient8NotSafeForScripting();
ax.OnLoginComplete += Ax_OnLoginComplete;
ax.OnLogonError += Ax_OnLogonError;
ax.OnFatalError += Ax_OnFatalError;
ax.Size = new Size(1, 1);
ax.CreateControl();
ax.Server = ipTbx.Text;
ax.UserName = userNameTbx.Text;
MsRdpClient8NotSafeForScripting sec = (MsRdpClient8NotSafeForScripting)ax.GetOcx();
sec.AdvancedSettings8.ClearTextPassword = passwordTbx.Text;
sec.AdvancedSettings8.EnableCredSspSupport = true;
ax.Connect();
} catch (Exception ex) {
MessageBox.Show("Error : " + ex.Message);
}
}
private void Ax_OnFatalError(object sender, IMsTscAxEvents_OnFatalErrorEvent e) {
SaySomething();
}
private void Ax_OnLogonError(object sender, IMsTscAxEvents_OnLogonErrorEvent e) {
SaySomething();
}
private void Ax_OnLoginComplete(object sender, EventArgs e) {
SaySomething();
}
public void SaySomething() {
MessageBox.Show("Worked!");
}
As you can see, I've done everything in the article way. But nothing happens, even an exception would be worthy.
Any Idea?

Combobox and timer in Visual Studio 2012

The code after edit is:
private void Form1_load(object sender, EventArgs e)
{
}
private void ComboBox1_SelectedIndexChanged(object sender, System.EventArgs e)
{
try
{
if (comboBox1.Text == "Present")
{
label47.Text = DateTime.Now.ToShortDateString();
label9.Text = DateTime.Now.ToShortTimeString();
}
}
catch (Exception)
{
}
}
}
}
use selected index changed event
private void ComboBox1_SelectedIndexChanged(object sender,System.EventArgs e)
{
try
{
if(ComboBox1.Text == "present")
{
label.Text = DateTime.Now.ToString(#"MM\/dd\/yyyy HH:mm");
}
}catch(Exception)
{
}
}

Objectlistview doubleclick explained

I'm trying to implement the doubleclick function in an objectlistview object.
According the developer, one should use ItemActivate instead of MouseDoubleClick.
So I came up with this:
private void treeListView_ItemActivate(object sender, EventArgs e)
{
try
{
ListView.SelectedIndexCollection col = treeListView.SelectedIndices;
MessageBox.Show(col[0].ToString());
}
catch (Exception e3)
{
globals.logfile.error(e3.ToString());
globals.logfile.flush();
}
finally
{
}
}
Which comes up with a value for each double clicked row.
But how do I get the details from that row?
Here's the whole solution I'm now using:
private void treeListView_ItemActivate(object sender, EventArgs e)
{
try
{
var se = (StructureElement)treeListView.GetItem(treeListView.SelectedIndex).RowObject;
MessageBox.Show(se.id.ToString());
}
catch (Exception e3)
{
globals.logfile.error(e3.ToString());
globals.logfile.flush();
}
finally
{
}
}
Which comes up with a value for each double clicked row. But how do I get the details from that row?
I think you have to access the RowObject using the underlying OLVListItem like this:
private void treeListView_ItemActivate(object sender, EventArgs e) {
var item = treeListView.GetItem(treeListView.SelectedIndex).RowObject;
}
This is how I'm now getting the data out of the treelistview:
private void treeListView_ItemActivate(object sender, EventArgs e)
{
try
{
var se = (StructureElement)treeListView.GetItem(treeListView.SelectedIndex).RowObject;
MessageBox.Show(se.id.ToString());
}
catch (Exception e3)
{
globals.logfile.error(e3.ToString());
globals.logfile.flush();
}
finally
{
}
}

How can I amend a record that I have inputting?

I am creating a To Do List using Windows Forms.
This is what I have so far.
The code for this form is as follows
namespace To_Do_List
{
public partial class To_Do_List : Form
{
public To_Do_List()
{
InitializeComponent();
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e) //this is the exit button on the toolstrip
{
Application.Exit(); //exits the program when the Exit button is clicked in dropdown menu
}
private void button4_Click(object sender, EventArgs e)//This creates the button to open the about form
{
AboutMyProgram aboutForm = new AboutMyProgram();
aboutForm.ShowDialog(); //opens about form
}
private void button3_Click(object sender, EventArgs e) //This creates the button to open the form which ammends tasks
{
AmmendItem CreateForm = new AmmendItem(this);
CreateForm.Show();
}
private void button1_Click(object sender, EventArgs e) // This creates the button to open the form which creates new tasks
{
AddItem CreateForm = new AddItem(this);
CreateForm.Show();
}
public void listView1_SelectedIndexChanged_1(object sender, EventArgs e) // This creates the table
{
}
private void button2_Click(object sender, EventArgs e) //This Allows the user to delete entries
{
if (listView1.SelectedItems != null)
{
var confirmation = MessageBox.Show(
"Are you sure you want to delete this?",
"WARNING", MessageBoxButtons.YesNo, MessageBoxIcon.Question
);
if (confirmation == DialogResult.Yes)
{
for (int i = listView1.Items.Count - 1; i >= 0; i--)
{
if (listView1.Items[i].Selected)
{
listView1.Items[i].Remove();
i--;
}
}
}
}
}
}
}
To add a task, the form looks like this
And again, the code is as follows
namespace To_Do_List
{
public partial class AddItem : Form
{
To_Do_List home;
public AddItem(To_Do_List parent)
{
InitializeComponent();
home = parent;
}
private void label1_Click(object sender, EventArgs e)
{
}
private void label1_Click_1(object sender, EventArgs e)
{
}
private void label2_Click(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
}
private void openListToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void sortByDateToolStripMenuItem_Click(object sender, EventArgs e)
{
}
public void dateTimePicker1_ValueChanged(object sender, EventArgs e)
{
}
public void textBox1_TextChanged(object sender, EventArgs e)//Title Box
{
}
public void /*Description of Task*/richTextBox1_TextChanged(object sender, EventArgs e)
{
}
public void /*Priority Box*/comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close(); //causes the window to close but keeps the application running
}
private void aboutToDoListToolStripMenuItem_Click(object sender, EventArgs e)
{
AboutMyProgram aboutForm = new AboutMyProgram();
aboutForm.ShowDialog(); //opens about form displaying copyright information
}
public void button1_Click(object sender, EventArgs e) //create task button
{
ListViewItem item1 = new ListViewItem(Title.Text);
item1.SubItems.Add(Description.Text);
item1.SubItems.Add(Priority.Text);
item1.SubItems.Add(Date.Text);
string value = "";
bool isChecked = Completed.Checked;
if (isChecked)
item1.SubItems.Add(Completed.Text);
else
value = null;
home.listView1.Items.Add(item1);
this.Close();
}
private void Date_ValueChanged(object sender, EventArgs e)
{
}
private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e) //Closes the window
{
this.Close();
}
}
}
The Amend form is exactly the same as the New Task form. How would I go about being able to select a record, pressing the amend button and actually changing?
I'm pretty stumped.
Also, this isn't really part of this question but I'll ask it just in case someone knows.
How would I go about being able to actually save these records so that they are there when I open the application back up again?
Thank you very much for reading, I know that I have just dumped everything but I'm really new to Windows Forms so I didn't want to accidentally miss something important out.
Edit
Am I on the right road with something like this?
public void button1_Click(object sender, EventArgs e)
{
To_Do_List editform = new To_Do_List(Title.Text);
editform.Description.Text = listView1.SelectedItems[0].SubItems[0].Text;
Still can't get it to work :/
This code for popup window.
public partial class frmToDoDetails : Form
{
public string TaskTitle { get; set; }
public string Description { get; set; }
public bool EditMode { get; set; }
public frmToDoDetails()
{
InitializeComponent();
}
private void btnSave_Click(object sender, EventArgs e)
{
TaskTitle = txtTitle.Text;
Description = txtDesc.Text;
this.DialogResult = System.Windows.Forms.DialogResult.OK;
}
private void frmToDoDetails_Load(object sender, EventArgs e)
{
if (EditMode)
{
txtTitle.Text = TaskTitle;
txtDesc.Text = Description;
}
else {
txtTitle.Text = string.Empty;
txtDesc.Text = string.Empty;
}
txtTitle.Focus();
}
}
And this for list
public partial class frmToDo : Form
{
public frmToDo()
{
InitializeComponent();
}
private void btnNew_Click(object sender, EventArgs e)
{
frmToDoDetails frm = new frmToDoDetails();
if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string[] arr = new string[2];
ListViewItem itm;
arr[0] = frm.TaskTitle;
arr[1] = frm.Description;
itm = new ListViewItem(arr);
listView1.Items.Add(itm);
}
}
private void frmToDo_Load(object sender, EventArgs e)
{
listView1.View = View.Details;
listView1.GridLines = true;
listView1.FullRowSelect = true;
//Add column header
listView1.Columns.Add("Title", 100);
listView1.Columns.Add("Desc", 70);
}
private void listView1_DoubleClick(object sender, EventArgs e)
{
ListViewItem currentItem= listView1.SelectedItems[0];
frmToDoDetails frm = new frmToDoDetails();
frm.TaskTitle = currentItem.SubItems[0].Text;
frm.Description = currentItem.SubItems[1].Text;
frm.EditMode = true;
if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
currentItem.SubItems[0].Text=frm.TaskTitle;
currentItem.SubItems[1].Text=frm.Description;
}
}
}
I am not added your complete fields(priority, date,etc..).
I hope it will help you.

Categories