private void pictureBox1_Paint_1(object sender, PaintEventArgs e)
{
Pen graphPen = new Pen(Color.Red, 2);
Point pt1D = new Point();
Point pt2D = new Point();
pt1D.X = textBox3.Text.ToString();
e.Graphics.DrawLine(graphPen, pt1D, pt2D);
}
我在第6行收到错误:cannot convert type string to int.
答案 0 :(得分:2)
其他人都是正确的,您需要转换价值,但仅使用int.Parse
可能会导致错误,val = int.TryParse
不是您使用int.TryParse
的方式,因此,更正:
int result = 0;
if (int.TryParse(textBox3.Text, out result)) {
pt1D.X = result;
} else {
// input isn't an integer
}
另外要提到的是Pen
实现IDisposable
,所以你应该在使用完之后处理它;您可以通过明确调用Dispose
或using
:
using (Pen graphPen = new Pen(Color.Red, 2)) {
// do what you need with the pen,
// it will be disposed when exiting this scope
}
答案 1 :(得分:1)
您需要将文本框中的字符串转换为整数:
private void pictureBox1_Paint_1(object sender, PaintEventArgs e)
{
Pen graphPen = new Pen(Color.Red, 2);
Point pt1D = new Point();
Point pt2D = new Point();
int xCoord = int.Parse(textBox3.Text);
pt1D.X = xCoord;
e.Graphics.DrawLine(graphPen, pt1D, pt2D);
}
答案 2 :(得分:0)
更改为:
private void pictureBox1_Paint_1(object sender, PaintEventArgs e)
{
int value = 0;
Pen graphPen = new Pen(Color.Red, 2);
Point pt1D = new Point();
Point pt2D = new Point();
pt1D.X = (int.tryParse(textBox3.Text, out value)) ? value : 0;
e.Graphics.DrawLine(graphPen, pt1D, pt2D);
}