list to handle array of doubles - c#

Is there a way to handle a list of doubles I can handle ints with the code below but not sure how to handle array of doubles.
{
CalculateSumOfList.ServiceReference1.Service1SoapClient client = new CalculateSumOfList.ServiceReference1.Service1SoapClient();
CalculateSumOfList.ServiceReference1.ArrayOfInt arrayOfInt = new CalculateSumOfList.ServiceReference1.ArrayOfInt();
arrayOfInt.AddRange(listDouble); // error here!
string result = client.CalculateSum(arrayOfInt);
label1.Text = Convert.ToString(result);
}
This is all wrong tho I need instead of ArrayOfInt to have Array of double?
Client Side:
namespace CalculateSumOfList
{
public partial class Form1 : Form
{
List<Double> listDouble = new List<Double>();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
listDouble.Add(Convert.ToDouble(textBox1.Text));
textBox1.Clear();
listBox1.Items.Clear();
for (int i = 0; i < listDouble.Count; i++)
{
listBox1.Items.Add(listDouble[i]);
}
textBox1.Clear();
listBox1.Items.Clear();
for (int i = 0; i < listDouble.Count; i++)
{
listBox1.Items.Add(listDouble[i]);
}
}
private void button2_Click(object sender, EventArgs e)
{
CalculateSumOfList.ServiceReference1.Service1SoapClient client = new CalculateSumOfList.ServiceReference1.Service1SoapClient();
CalculateSumOfList.ServiceReference1.ArrayOfInt arrayOfInt = new CalculateSumOfList.ServiceReference1.ArrayOfInt();
arrayOfInt.AddRange(listDouble); // error here!
string result = client.CalculateSum(arrayOfInt);
label1.Text = Convert.ToString(result);
}
}
}
Web Method:
namespace CalculateWebServiceSum
{
/// <summary>
/// Summary description for Service1
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class Service1 : System.Web.Services.WebService
{
[WebMethod]
public string CalculateSum(List<double> listDouble)
{
return listDouble.Sum().ToString();
}
}
}

I'm not clear what your question is, but:
If arrayOfInt.AddRange( listOfDouble ) is not compiling you could use Linq and do
arrayOfInt.AddRange( listOfDouble.Select( d => (int)d ).ToList() );
The method client.CalculateSum expects a parameter of type List<double>
1) I would change that if possible to be public string CalculateSum(IEnumerable<double> items) which is more flexible
2) As above you can convert a list of any convertible type using list.Select(n => (double)n).ToList() assuming that (double)n is a valid cast.

If I understand your question properly, you need to call ConvertAll to a type of decimal before you can add the listOfDecimal.
var convertedDecimalList = arrayOfInt.ConvertAll<decimal>
(element => (decimal)element);
convertedDecimalList.AddRange(listDecimal);
UPDATED:
CalculateSumOfList.ServiceReference1.Service1SoapClient client =
new CalculateSumOfList.ServiceReference1.Service1SoapClient();
CalculateSumOfList.ServiceReference1.ArrayOfInt arrayOfInt =
new CalculateSumOfList.ServiceReference1.ArrayOfInt();
var listOfIntAsDouble = arrayOfInt.ConvertAll(x=>Convert.ToDouble(x));
listOfIntAsDouble .AddRange(listDouble);
string result = client.CalculateSum(listOfIntAsDouble);
label1.Text = Convert.ToString(result);

Related

How can the scope be changed in a WinForms app to carry variables from a method to an object sender?

I am trying to carry the variables from the array over to the button click action. I can't find the way to set the scope to allow for this to work.
I have tried changing the modifiers to public, private, static, void, string, string[] etc.
I have also made all of the objects in the WinForms app set to Public
public partial class AutoPay : Form
{
public AutoPay()
{
InitializeComponent();
}
public void HeaderInformation(string dateAndTime, string fileNumber)
{
dateAndTime = DateTime.Now.ToString();
fileNumber = txtFileNumber.Text;
string[] headerArray = new string[2];
headerArray[0] = dateAndTime;
headerArray[1] = fileNumber;
}
public void BtnSave_Click(object sender, EventArgs e)
{
HeaderInformation(headerArray[0], headerArray[1]);
}
}
the headerArray[0] under the BtnSave_Click action has the red line under it showing that it is outside of the scope.
Try declaring the headerArray as a Property of the class
As was mentioned... you need to declare the headerArray outside the method... Also... it looks like you are trying to add information to the array before the array has information... try it this way(there are many other ways to do this too ;) ):
public partial class AutoPay : Form
{
private string[] headerArray; // <-- declare it here...
public AutoPay()
{
InitializeComponent();
headerArray = new string[2]; // <-- sometimes the normal way to initialize...
}
public void HeaderInformation(string dateAndTime, string fileNumber)
{
// reinitialize headerArray for safety....
headerArray = new string[2];
headerArray[0] = dateAndTime;
headerArray[1] = fileNumber;
}
public void BtnSave_Click(object sender, EventArgs e)
{
HeaderInformation(DateTime.Now.ToString(), txtFileNumber.Text);
}
}
or
public void HeaderInformation()
{
// reinitialize headerArray for safety....
headerArray = new string[2];
headerArray[0] = DateTime.Now.ToString();
headerArray[1] = txtFileNumber.Text;
}
public void BtnSave_Click(object sender, EventArgs e)
{
HeaderInformation();
}

C# Copying and pasting an object

So I'm trying to copy and paste an object and having trouble getting it right. I've searched through the topics but I still can't seem to get it to work. Here is the code:
In one solution in Visual studio I have the the class:
namespace test4
{
[Serializable]
public class copypaste
{
public string test = "a";
}
}
and the copy part of the code:
private void btn1_Click(object sender, EventArgs e)
{
var copy_obj = new copypaste();
DataObject d = new DataObject(copy_obj);
Clipboard.SetDataObject(d);
}
And in another solution I have:
namespace test4
{
[Serializable]
public class copypaste
{
public string test = "a";
}
}
and the paste part of the code:
private void btnTest_Click(object sender, EventArgs e)
{
var d = Clipboard.GetDataObject();
if (d.GetDataPresent("test4.copypaste"))
{
var o = d.GetData("test4.copypaste");
Debug.WriteLine( ( (copypaste)o ).test );
}
}
However, I end up with the following error on the final line:
'System.InvalidCastException: 'Unable to cast object of type 'System.IO.MemoryStream' to type 'test4.copypaste'.'
I have gone through other questions which suggest this way of copy/pasting code but none seem to return memory stream when they call the GetData method. I am unsure how to extract the object from the memory stream.
Thanks
With this reference in mind and with your serializable class, this works as expected:
private void copyButton_Click(object sender, EventArgs e)
{
DataFormats.Format myFormat = DataFormats.GetFormat("test4.copypaste");
var copy_obj = new copypaste();
DataObject myDataObject = new DataObject(myFormat.Name, copy_obj);
Clipboard.SetDataObject(myDataObject);
}
private void pasteButton_Click(object sender, EventArgs e)
{
var d = Clipboard.GetDataObject();
if (d.GetDataPresent("test4.copypaste"))
{
var o = d.GetData("test4.copypaste");
Debug.WriteLine(((copypaste)o).test);
}
}

MessageBox doesn't show the variable

I have a list variable and I created an iterator for it to print out its content. It's working in the console application but when i try to do it using windows form(gui) it doesn't work
PROGRAM.CS
namespace gui
{
static class Program
{
public class studentdata
{
public string id, name, password, academicyear, finishedcourseslist, ipcourseslist;
public int noCoursesF, noCoursesIP;
public List<string> coursesF;
public List<string> coursesIP;
public studentdata()
{
id = "2015123";
password = "Student";
coursesF = new List<string>();
coursesIP = new List<string>();
}
public studentdata(string ID, string NAME, string PASSWORD)
{
id = ID;
}
**public void view_finished_courses()
{
List<string> finished = coursesF;
foreach (string n in finished)
{
finishedcourseslist += n;
}
MessageBox.Show(finishedcourseslist, "Finished courses");
}
public void view_ip_courses()
{
List<string> progress = coursesIP;
foreach (string m in progress)
{
ipcourseslist += m;
}
MessageBox.Show(ipcourseslist, "Finished courses");
}**
}
public class Admin
{
public string name, password;
public Admin()
{
name = "Admin";
password = "Admin";
}
}
//functionssssss
internal static studentdata studentSearch(string IDsearch)
{
FileStream FS = new FileStream("Students.txt", FileMode.Open);
StreamReader SR = new StreamReader(FS);
studentdata std = new studentdata();
while (SR.Peek() != -1)
{
string z = SR.ReadLine();
String[] Fields;
Fields = z.Split(',');
if (IDsearch.CompareTo(Fields[0]) == 0)
{
std.id = Fields[0];
std.password = Fields[1];
std.name = Fields[2];
std.noCoursesF = int.Parse(Fields[3]);
int currentField = 4;
for (int course = 0; course < std.noCoursesF; course++)
{
std.coursesF.Add(Fields[currentField]);
currentField++;
}
std.noCoursesIP = int.Parse(Fields[currentField]);
currentField++;
for (int course = 0; course < std.noCoursesIP; course++)
{
std.coursesIP.Add(Fields[currentField]);
currentField++;
}
std.academicyear = Fields[currentField];
SR.Close();
return std;
}
else continue;
}
SR.Close();
studentdata araf = new studentdata();
return araf;
}
}
FORM.CS
namespace gui
{
public partial class Form3 : Form
{
Program.studentdata student = new Program.studentdata();
public Form3()
{
InitializeComponent();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void button5_Click(object sender, EventArgs e)
{
}
private void button4_Click(object sender, EventArgs e)
{
student.view_finished_courses();
}
private void button6_Click(object sender, EventArgs e)
{
student.view_ip_courses();
}
}
}
The output is an empty message box, I don't know why variable isn't added.
Replace messagebox line with
MessageBox.Show(string.Join(",", coursesF.ToArray()), "Finished courses");
It seems like your code is incomplete. Nowhere in the code which gets executed after you clicked button4 you are adding items to coursesF. It seems that you are adding items in this line: std.coursesF.Add(Fields[currentField]);
This line is in your function studentSearch(IDsearch), the function never gets called.
In this function you got a string z in which all the data of a student is saved (string z = SR.ReadLine()). You must somehow fill this string z. You can use a TextBox in your form and pass the value into the string, use a string from a text file or use the console input(see here: Get input from console into a form).
As you can see the issue is not a one line fix.

Assigned values to a variable in a class from Button click event outside. But returning zero as output from another button click

Here I have a variable in a class and trying to give input and get output from through buttons outside the class. But when I am creating new object to a class (button2), I am not getting output values given (button1).
class dataconversion
{
public List<decimal> sample = new List<decimal>();
public void dataconvert(List <decimal> transfer)
{
string filedata;
Stream filestream;
OpenFileDialog opendialog = new OpenFileDialog();
if (opendialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
if ((filestream = opendialog.OpenFile()) != null)
{
filedata = System.IO.File.ReadAllText(opendialog.FileName);
List<string> stringlist = new List<string>(filedata.Split(' ', '\n', '\t'));
stringlist = stringlist.Where(val => val != "").ToList();
List<decimal> decimallist = stringlist.ConvertAll(s => decimal.Parse(s));
transfer.AddRange(decimallist);
}
}
}
}
public class methodacess
{
dataconversion dc = new dataconversion();
public void sampleaccess()
{
dc.dataconvert(dc.sample);
}
public void messages()
{
MessageBox.Show(dc.sample.Count.ToString());
}
//output is giving only zeros.
}
private void button1_Click(object sender, EventArgs e)
{
methodacess ma = new methodacess();
ma.sampleaccess();
}
private void button4_Click(object sender, EventArgs e)
{
methodacess ma4 = new methodacess();
ma4.messages();
}
}
Your problem is this line in button4_Click:
methodacess ma4 = new methodacess();
You are creating a brand new instance of methodacess.
In fact the one you created in button1_Click is not stored anywhere and is lost after the method exits.
So your call to ma.sampleaccess(); is on a different instance to the call on ma4.messages(); so no wonder there is no data.
Now, I don't like the way you've structured your classes. It's really a bit odd, but sticking with this structure here's how I would write it.
First, dataconversion - make it static with a single function that returns a new copy of the list.
public static class dataconversion
{
public static List<decimal> dataconvert()
{
var filedata = "";
using (var opendialog = new OpenFileDialog())
{
if (opendialog.ShowDialog() == DialogResult.OK)
{
if (System.IO.File.Exists(opendialog.FileName))
{
filedata = System.IO.File.ReadAllText(opendialog.FileName);
}
}
}
return
filedata
.Split(' ', '\n', '\t')
.Where(val => val != "")
.Select(s => decimal.Parse(s))
.ToList();
}
}
Now, methodaccess - notice it now just holds the actual list of decimals:
public class methodacess
{
List<decimal> data = new List<decimal>();
public void sampleaccess()
{
data = dataconversion.dataconvert();
}
public void messages()
{
MessageBox.Show(data.Count.ToString());
}
}
And finally your UI calling code:
private methodacess ma = new methodacess();
private void button1_Click(object sender, EventArgs e)
{
ma.sampleaccess();
}
private void button4_Click(object sender, EventArgs e)
{
ma.messages();
}
Note that there is a single instance of methodaccess.

I cant call my method from class in form

Im new to c# and programming
i can make the method Work, but not when i try to call it from my class 'Admin', it think its just a minor problem, but im just stuck ... Again.. No overload for method "opretspejder" takes 0 arguments
any help help i would be glad
Here my class
public class Admin
{
public static void OpretSpejder(string Snavn_txt, string Senavn_txt, string Sa_txt, string Scpr_txt)
{
{
if (!(string.IsNullOrEmpty(Snavn_txt)))
if (!(string.IsNullOrEmpty(Senavn_txt)))
if (!(string.IsNullOrEmpty(Sa_txt)))
if (!(string.IsNullOrEmpty(Scpr_txt)))
{
XmlDocument doc = new XmlDocument();
doc.Load(#"Spejder.xml");
var nodeCount = 0;
using (var reader = XmlReader.Create(#"Spejder.xml"))
{
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element &&
reader.Name == "Spejder")
{
nodeCount++;
}
}
}
nodeCount++;
XmlElement Spejder = doc.CreateElement("Spejder");
Spejder.SetAttribute("ID", nodeCount.ToString());
XmlNode Navn = doc.CreateElement("Navn");
Navn.InnerText = Snavn_txt;
Spejder.AppendChild(Navn);
XmlNode Efternavn = doc.CreateElement("Efternavn");
Efternavn.InnerText = Senavn_txt;
Spejder.AppendChild(Efternavn);
XmlNode Alder = doc.CreateElement("Alder");
Alder.InnerText = Sa_txt;
Spejder.AppendChild(Alder);
XmlNode Cpr = doc.CreateElement("Cpr");
Cpr.InnerText = Scpr_txt;
Spejder.AppendChild(Cpr);
doc.DocumentElement.AppendChild(Spejder);
doc.Save(#"Spejder.xml");
Snavn_txt = String.Empty;
Senavn_txt = String.Empty;
Sa_txt = String.Empty;
Scpr_txt = String.Empty;
// MessageBox.Show("Spejder Oprettet");
}
}
and here is the buttonclick i want to execute my method:
private void button2_Click(object sender, EventArgs e)
{
Admin.OpretSpejder();
}
The declaration of your method says
public static void OpretSpejder(string ..., string ...., string ...., string ....)
but you call it without passing any of the 4 strings required
Admin.OpretSpejder();
Of course the compiler is not happy
It seems that the method OpretSpejder wants to create an XML file with 4 elements and these 4 elements are required because without them the whole block of code is skipped, so you have no alternative than passing the 4 strings required
If you are the author of OpretSpejder then I think that you should know what to pass at the calling point, otherwise you should ask the author of the code what are these four parameters
You've declared OpretSpejder method with 4 mandatory string arguments
(Snavn_txt, Senavn_txt, Sa_txt, Scpr_txt):
public class Admin {
public static void OpretSpejder(string Snavn_txt, string Senavn_txt, string Sa_txt, string Scpr_txt) {
...
So If you want to call this method you should either provide these arguments:
private void button2_Click(object sender, EventArgs e) {
string Snavn_txt = "..."; // <- Put your real values here
string Senavn_txt = "...";
string Sa_txt = "...";
string Scpr_txt = "...";
Admin.OpretSpejder(Snavn_txt, Senavn_txt, Sa_txt, Scpr_txt);
}
or as compiler suggested create an overload version of OpretSpejder with no arguments:
public class Admin {
// New overloaded version
public static void OpretSpejder() {
...
}
// Old version
public static void OpretSpejder(string Snavn_txt, string Senavn_txt, string Sa_txt, string Scpr_txt) {
...
public partial class Form1 : System.Windows.Forms.Form
{
public Form1()
{
InitializeComponent();
}
Admin classAdmin = new Admin();
private void button2_Click(object sender, EventArgs e)
{
classAdmin.OpretSpejder("yourstring1","yourstring2","yourstring3","yourstring4"); //Admin.OpretSpejder();
}
}

Categories