how to separate the selected items in a checkbox? - c#

I have two forms in WFA C#.
FORM1:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication8
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
if (checkBox1.Checked == true)
{
f2.intr = checkBox1.Text;
}
if (checkBox2.Checked == true)
{
f2.intr2 = checkBox2.Text;
}
if (checkBox3.Checked == true)
{
f2.intr3 = checkBox3.Text;
}
if (checkBox4.Checked == true)
{
f2.intr4 = checkBox4.Text;
}
if (checkBox5.Checked == true)
{
f2.intr5 = checkBox5.Text;
}
f2.ShowDialog();
}
}
}
FORM2:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication8
{
public partial class Form2 : Form
{
public string gen, intr, intr2, intr3, intr4, intr5;
public string interest
{
get { return intr; }
set { intr = value; }
}
public string interest2
{
get { return intr2; }
set { intr2 = value; }
}
public string interest3
{
get { return intr3; }
set { intr3 = value; }
}
public string interest4
{
get { return intr4; }
set { intr4 = value; }
}
public string interest5
{
get { return intr5; }
set { intr5 = value; }
}
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
label1.Text = "Interests: " + interest + "\n" + interest2 + "\n" + interest3 + "\n" + interest4 + "\n" + interest5;
}
}
}
I have 5 checkboxes inside a groupbox. This outputs the selected items to label1. The output looks like this when I check all the checkboxes:
art
science
math
history
sports
and whenever I check boxes randomly for example i'll check the art and history. The output is like this:
art
history
it leaves two spaces.
In the design of form1 there are the checkbox1,checkbox2,checkbox3,checkbox4,checkbox5 inside a groupbox.
In the design of form2 there is only label1.
How can I separate the selected items by a comma in one line?
I'm new to c# helpp.

You could put all the interests in an array:
string[] interests = { interest, interest2, interest3, interest4, interest5 };
Then you could remove the non-selected ones:
string[] selectedInterests = interests.Where(str => !String.IsNullOrEmpty(str)).ToArray();
At the end you can join them into a single string:
label1.Text = String.Join(", ", selectedInterests);

Related

C# duplicate component name

I have created a UserControl which has 2 properties.
See my code here:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.ComponentModel.Design;
namespace Controls
{
public partial class UserControl1: Panel
{
bool reset = false;
public bool _reset
{
get { return reset; }
set
{
reset = value;
if (value == true)
{
this.Controls.Clear();
cntCount = 0;
reset = false;
}
}
}
int cntCount = 0;
public int _cntCount
{
get { return cntCount; }
set
{
cntCount = value;
populate();
}
}
public UserControl1()
{
InitializeComponent();
}
void populate()
{
this.Controls.Clear();
IDesignerHost mDes = null;
mDes = (IDesignerHost)GetService(typeof(IDesignerHost));
for (int t = 0; t < cntCount; t++)
{
Button b = mDes.CreateComponent(typeof(Button), GenerateNewPaneName()) as Button;
this.Controls.Add(b);
}
}
protected string GenerateNewPaneName()
{
int curNum = 1;
bool bDuplicateName;
IReferenceService refsvc = GetService(typeof(IReferenceService)) as IReferenceService;
string curTry;
// Get a new component name
do
{
curTry = "b_" + curNum;
bDuplicateName = (refsvc.GetReference(curTry) != null);
curNum++;
}
while (bDuplicateName);
return curTry;
}
}
}
Dragging that control on the form is no problem.
If I enter a number into the property _cntCount, the control adds the required number of buttons inside my UserControl; no problem.
If I save the Form, close and reopen it, I get an error:
Duplicate component name 'b_1'. Component names must be unique and case-insensitive.
What do I miss?
Thanks in advance,
Murat

Why does ap.Connect(authrequest) return a null value?

I am having a problem with my code where i run into an error when i try to click the join button. It says the ap.Connect(authrequest) is returning a null value so it cannot return a bool value. I am doing this in visual studio in a .net forms i think.
Thanks for you help.
Ps i am a student
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using SimpleWifi;
namespace desk_flat
{
public partial class formConnect : Form
{
private static Wifi wifi;
public formConnect()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
wifi = new Wifi();
List<AccessPoint> aps = wifi.GetAccessPoints();
foreach (AccessPoint ap in aps)
{
ListViewItem listobj = new ListViewItem(ap.Name);
listobj.SubItems.Add(ap.SignalStrength + "'''");
listobj.Tag = ap;
lstWifi.Items.Add(listobj);
}
}
private bool ConnectWifi(AccessPoint ap, string password)
{
AuthRequest authrequest = new AuthRequest(ap);
authrequest.Password = password;
return ap.Connect(authrequest);
}
private void btnJoin_Click(object sender, EventArgs e)
{
if (lstWifi.Items.Count > 0 && txtbPassword.Text.Length > 0)
{
ListViewItem selectedItem = lstWifi.SelectedItems[0];
AccessPoint ap = (AccessPoint)selectedItem.Tag;
if (ConnectWifi(ap, txtbPassword.Text))
{
lblStatus.Text = "You have connected to " + ap.Name;
}
else
{
lblStatus.Text = "Connection has failed";
}
}
else
{
lblStatus.Text = "Enter a password or select a network";
}
}
}
}

How do I get a string from a TextBox in VS and then compare it to an integer using an if statement?

Alright, I'm pretty new to C# and I'm trying to figure out how I could grab a string or a number from my TextBox in Visual Studio(Windows Form Application) and then figure out if that string is 0.
I've tried doing
if(Calculations.Text == 0)
{
Calculations.Text = 1
}
but to my avail it did not work.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Calculatrice : Form
{
public Calculatrice()
{
InitializeComponent();
}
private void One_Click(object sender, EventArgs e)
{
if(Calculations.Text)
{
}
}
private void Calculatrice_Load(object sender, EventArgs e)
{
}
}
}
This is all I have right now I'm pretty stuck.
I want to be able to use the if statement to make comparisons with int values.
You should enclose your string in quotes before using them
if(Calculations.Text.Trim () == "0")
{
Calculations.Text = "1";
}
//Example:if Calculations is your textbox id,then
string input = calculations.text.tostring();
//then compare zero with " "
if(input == "0")
{
calculations.text= 1;
}
A user can put anything in a TextBox. Use TryParse which will provide a zero even if it fails (returns false)
private void OPCode()
{
int.TryParse(Calculations.Text, out int i);
if (i == 0)
{
Calculations.Text = 1.ToString();
}
}

Entering data into Excel worksheets in an add in (C#)

I'm creating an add in for Microsoft Excel that includes a ribbon tab. On this tab is a button with the following code:
public void setAccounts()
{
foreach (Excel.Worksheet displayWorksheet in Globals.ThisAddIn.Application.Worksheets)
{
displayWorksheet.Range[budget_cell].Value2 = "$" + Convert.ToString(budget);
displayWorksheet.Range[account_cell].Value2 = "$0.00";
displayWorksheet.Range[transaction_cell].Value2 = "Amount";
}
}
The button opens up a separate form where the user specifies budget_cell, account_cell, and transaction_cell. I then pass that data to the above code in SolutionName.ThisAddIn.cs (where SolutionName is the namespace of the solution). Strictly speaking, the code works. However, the data doesn't show up in the cells until the button is pressed a second time. Why is that? Is it because I'm retrieving the data from a different object in the solution?
Also, I've been trying to get this code and the aforementioned form to activate when the add in first starts up.
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
frmStartup startup = new frmStartup();
startup.Show();
setAccounts();
}
I've been at this for a good twelve hours now, and I can't get it to work. What am I missing?
ThisAddIn.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using Excel = Microsoft.Office.Interop.Excel;
using Office = Microsoft.Office.Core;
using Microsoft.Office.Tools.Excel;
namespace AccountingAddIn
{
public partial class ThisAddIn
{
public static string budget_cell = "";
public static string account_cell = "";
public static string transaction_cell = "";
public static string date_cell = "";
public static string time_cell = "";
public static string description_cell = "";
public static bool date = false;
public static bool time = false;
public static bool description = false;
public static decimal budget = 0;
List<Account> accounts = new List<Account>();
public void budgetStartUp()
{
frmStartup startup = new frmStartup();
startup.Show();
setAccounts();
}
public void setAccounts()
{
foreach (Excel.Worksheet displayWorksheet in Globals.ThisAddIn.Application.Worksheets)
{
displayWorksheet.Range[budget_cell].Value2 = "$" + Convert.ToString(budget);
displayWorksheet.Range[account_cell].Value2 = "$0.00";
displayWorksheet.Range[transaction_cell].Value2 = "Amount";
if (date == true)
{
displayWorksheet.Range[date_cell].Value2 = "Date";
}
if (time == true)
{
displayWorksheet.Range[time_cell].Value2 = "Time";
}
if (description == true)
{
displayWorksheet.Range[description_cell].Value2 = "Description";
}
Account na = new Account(0, displayWorksheet);
accounts.Add(na);
}
}
protected override Microsoft.Office.Core.IRibbonExtensibility CreateRibbonExtensibilityObject()
{
return Globals.Factory.GetRibbonFactory().CreateRibbonManager(
new Microsoft.Office.Tools.Ribbon.IRibbonExtension[] { new MyRibbon() });
}
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
CreateRibbonExtensibilityObject();
budgetStartUp();
}
private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
{
}
}
}
frmStartup.cs:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace AccountingAddIn
{
public partial class frmStartup : Form
{
public frmStartup()
{
InitializeComponent();
}
private void btnHelp_Click(object sender, EventArgs e)
{
MessageBox.Show("Please enter a starting amount for your budget and " +
"which cells will display the running total for your " +
"accounts." +
"\n\nNote: Leaving the budget blank will" +
" result in a starting budget of $0.00.");
}
private void btnOkay_Click(object sender, EventArgs e)
{
AccountingSeminar.ThisAddIn.budget += Convert.ToDecimal(txtStartingAmount.Text);
AccountingSeminar.ThisAddIn.budget_cell = txtBudget.Text;
AccountingSeminar.ThisAddIn.account_cell = txtAccount.Text;
AccountingSeminar.ThisAddIn.transaction_cell = txtTransaction.Text;
if (chkDate.Checked)
{
AccountingSeminar.ThisAddIn.date_cell = txtDate.Text;
AccountingSeminar.ThisAddIn.date = true;
}
if (chkTime.Checked)
{
AccountingSeminar.ThisAddIn.time_cell = txtTime.Text;
AccountingSeminar.ThisAddIn.time = true;
}
if (chkDescription.Checked)
{
AccountingSeminar.ThisAddIn.description_cell = txtDescription.Text;
AccountingSeminar.ThisAddIn.description = true;
}
Close();
}
}
}

Return Value Between Classes

How do I get a button click on a form to send the return of a called method to another class? Here is the pseudo code of what I have and any help would be greatly appreciated...
[Class Library]
using System;
using System.Runtime.InteropServices;
using System.Text;
using System.Collections.Generic;
using System.Linq;
namespace Auto
{
GUID Info
public interface IAuto
{
string SendToOtherApp();
}
COM Info
public class Auto : IAuto
{
public string tbox1;
NAVForm frm1 = new NAVForm();
public Auto()
{
}
public string SendToOtherApp()
{
frm1.ShowDialog();
tbox1 = NAVForm.UseThis();
return tbox1;
}
}
}
[Form]
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Auto
{
public partial class NAVForm : Form
{
public NAVForm()
{
InitializeComponent();
}
private void NAVForm_Load(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
UseThis(textBox1.Text);
}
public string UseThis(string txt)
{
if (txt.Trim().Length != 0)
{
return txt;
}
else
{
return "didn't work";
}
}
}
}
I want to get the return value from public string UseThis(string txt) into public string SendToOtherApp() which is visible to the other system that is calling this.
I am obviously new to C# so I am also very open to an overall critique of the project and best practices.
This is what I have done and it works great. In our ERP I run the codeunit, which calls the automation variable which is tied to the "OpenThis()" method. My form opens, I enter text in the textbox, click OK, it closes the from and the ERP pops a messagebox displaying the text from the message box. What do you C# experts think about this build? I am very interested in your thoughts on this solution so please let me know.
Class Library.....
using System;
using System.Runtime.InteropServices;
using System.Text;
using System.Collections.Generic;
using System.Linq;
namespace NavAutomation
{
[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
[Guid("5D83B4FE-45E6-410E-A075-AD635F5F0354")]
[ComVisible(true)]
public interface INavAutomation
{
string HelloWorld();
object OpenThis();
}
[ComVisible(true)]
[Guid("B7806CE5-862A-4407-9A3E-14CE8A9FB83A")]
[ClassInterface(ClassInterfaceType.None)]
public class NavAutomation : INavAutomation
{
public NavAutomation()
{
}
public object OpenThis()
{
using (var form = new NAVForm())
{
var result = form.ShowDialog();
return form.RetVal1;
}
}
}
}
Form.....
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace NavAutomation
{
public partial class NAVForm : Form
{
public NAVForm()
{
InitializeComponent();
}
private void NAVForm_Load(object sender, EventArgs e)
{
}
public string RetVal1 { get; set; }
private void button2_Click(object sender, EventArgs e)
{
if (textBox1.Text.Trim().Length != 0)
{
this.RetVal1 = textBox1.Text;
}
else
{
this.RetVal1 = "didn't work";
}
this.Close();
}
}
}
I am not sure if i got your goals right but here is the code that when called from a from, shows another modal form with a textbox, you enter a value into that textbox and close this modal form to find that value in that textbox returned to the first form that called for the show of the modal form.
CLASS LIBRARY
using System;
using System.Runtime.InteropServices;
using System.Text;
using System.Collections.Generic;
using System.Linq;
namespace Auto
{
public interface IAuto
{
string SendToOtherApp();
}
public class Auto : IAuto
{
public string tbox1;
NAVForm frm1 = new NAVForm();
public Auto()
{
}
public string SendToOtherApp()
{
frm1.ShowDialog();
tbox1 = frm1.UseThis(frm1.textBox1.Text);
return tbox1;
}
}
}
A FROM THAT CALLS TO SHOW A MODAL FORM
namespace Auto
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Auto auto = new Auto();
string returnedString = auto.SendToOtherApp(); // the string filled at the modal form text boxed will be returned to this variable
}
}
THE FORM THAT WILL BE SHOWED AS MODAL FORM
namespace Auto
{
public partial class NAVForm : Form
{
public NAVForm()
{
InitializeComponent();
}
public string UseThis(string txt)
{
if (txt.Trim().Length != 0)
{
return txt;
}
else
{
return "didn't work";
}
}
private void button1_Click(object sender, EventArgs e)
{
UseThis(textBox1.Text);
}
}
}
Please note that the access modifier of textBox1 at NAVForm should be set to public in order for it to be visible to class Auto
Let me know if i misunderstood something to correct it.

Categories