如何在每次崩溃应用程序时处理此错误?

时间:2015-12-26 17:43:04

标签: c#

错误:

  

System.IndexOutOfRangeException

中发生了System.Data.dll类型的未处理异常      

附加信息:位置1没有行。

代码:

private void Form11_Load(object sender, EventArgs e) {
    SqlConnection con = new SqlConnection(@"Data Source=(localdb)\ProjectsV12;Initial Catalog=Hospital;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;");
    SqlDataAdapter sda = new SqlDataAdapter("SELECT Name FROM Patient where Patient_ID = '" + textBox1.Text + "';", con);
    DataTable dt = new DataTable();
    sda.Fill(dt);

    textBox2.Text = dt.Rows[1]["Name"].ToString();
 }

每当我点击此页面的按钮时,它都会显示异常。我希望得到这个名字,但它每次都会给出这个未处理的例外。

1 个答案:

答案 0 :(得分:2)

如果你连续回来,你需要检查

这样的事情:

private void Form11_Load(object sender, EventArgs e) {
    SqlConnection con = new SqlConnection(@"Data Source=(localdb)\ProjectsV12;Initial Catalog=Hospital;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;");

    SqlDataAdapter sda = new SqlDataAdapter("SELECT Name FROM Patient where Patient_ID = @PatientID;", con);
    sda.SelectCommand.Parameters.Add("@PatientID", SqlDbType.Int).Value =  Convert.ToInt32(textBox1.Text);

    DataTable dt = new DataTable();
    sda.Fill(dt);

    // make sure to **CHECK** whether you actually **HAVE** a row!!
    if(dt.Rows.Count > 0)
    {
        // also: .Rows is **null-based** - the first entry is [0] ....
        textBox2.Text = dt.Rows[0]["Name"].ToString();
    }
 }