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);
}
}
Related
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();
}
I have tried to get the textbox.text to a class and it doesent work what am I am doing wrong please help!
In my form.cs it looks like this:
public string score1;
public void getPlayerOneScore1Input()
{
score1 = playerOneScore1TextBox.Text;
}
public void playerOneAddScoreButton_Click(object sender, EventArgs e)
{
score1Calculator theCalculator = new score1Calculator(score1);
}
and in my CLASS it looks like this:
class score1Calculator
{
public score1Calculator(string score1)
{
this.score1= score1;
}
public int playerOneDart1Value;
public void calculateDart1()
{
if (score1== "t1" || score1== "T1" || score1== "3")
{
playerOneDart1Value = 3;
}
else
{
MessageBox.Show("Dart 1! This is not a valid input!");
return;
}
}
}
error i get:
'WindowsFormApplication1.score1Calculator' does not contain a definition for 'player' and no extension method 'player' accepting a first argument of type 'WindowsFormApplication1.score1Calculator' could be found (are you missing a using directive or an assembly reference?)
There is no need to do it overly complicated. A Textbox.Text value is just a string. You can directly call the constructor with this reference.
Just write it like this
score1Calculator theCalculator = new dart1Calculator(playerOneScore1TextBox.Text);
No need to store the value on module level.
you dont call getPlayerOneScore1Input() in order the score1 to be assigned, in Form1 try:
public void playerOneAddScoreButton_Click(object sender, EventArgs e)
{
getPlayerOneScore1Input();
score1Calculator theCalculator = new dart1Calculator(score1);
}
On button click you are not calling your function getPlayerOneScore1Input() which actually assign value to score1.
public void playerOneAddScoreButton_Click(object sender, EventArgs e)
{
getPlayerOneScore1Input();
score1Calculator theCalculator = new dart1Calculator(score1);
}
Instead of assigning value to score1 in form class and assign it to your class member field. You may try this.
public void playerOneAddScoreButton_Click(object sender, EventArgs e)
{
if (!String.IsNullOrEmpty(playerOneScore1TextBox.Text))
{
score1Calculator theCalculator = new dart1Calculator(playerOneScore1TextBox.Text);
}
}
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.
T I'm having lots of trouble trying to get my code's speech synthesis class to recite words from a ListBoxItem.toString().
the foreach loop in the btnStart_Clicked() method is where i believe the problem starts:
test = testLstSet.lstWordlist.Items.ToString();
speech.SpeakAsync(test);
the speech synth tells me:
"system.windows.forms.listbox + object.collections"
could someone please help? sorry about all the code but i wanted to give you as much info as possible.
what am i doing wrong?
public partial class MyClass : Form
{
private bool testStarted = false;
private SpeechSynthesizer speech;
private string evalWord = null;
string test;
bool testBit = false;
TestList testLstSet;
public SpellingBee(TestList tstLst)
{
InitializeComponent();
testLstSet = tstLst;
speech = new SpeechSynthesizer();
speech.SpeakAsync("Hello! Welcome to The test. Shall we begin?");
}
private void btnStart_Click(object sender, EventArgs e)
{
if (testStarted)
return;
else
{
testStarted = true;
foreach(var item in wrdLstSet.lstWordlist.Items)
{
test = testLstSet.lstWordlist.Items.ToString();
speech.SpeakAsync(test);
while(!testBit)
{
}
}
}
}
private void btnSubmit_Click(object sender, EventArgs e)
{
string evalWord = this.txtAnswer.Text;
bool answer = string.Equals(evalWord, test, StringComparison.OrdinalIgnoreCase);
if (answer)
{
speech.SpeakAsync("That's right! Good Job!");
testbit = true;
}
else
{
speech.SpeakAsync("That is incorrect.");
testbit = true;
}
}
}
}
I don't really understand what you want to achieve but I think you need part of your code to
foreach(var item in testLstSet.lstWordlist.Items)
{
speech.SpeakAsync(item.ToString());
}
When you call testLstSet.lstWordlist.Items.ToString(); - you are getting type of Items, that is object.collections. If you want to get element of this collection you should use indexer like this: testLstSet.lstWordlist.Items[0].ToString();
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);