-3
    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);

    }  

I'm getting error on 6th line as: cannot convert type string to int.

4

3 回答 3

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
}

另一件要提到的是Penimplements IDisposable,所以你应该在用完这个东西后处理它;您可以通过显式调用Dispose或使用 a来执行此操作using

using (Pen graphPen = new Pen(Color.Red, 2)) {
  // do what you need with the pen, 
  // it will be disposed when exiting this scope
}
于 2013-06-15T15:38:26.607 回答
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);

}  
于 2013-06-15T15:35:20.080 回答
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);

}  
于 2013-06-15T15:35:29.523 回答