如何在每次应用程序崩溃时处理此错误
本文关键字:处理 错误 崩溃 应用程序 | 更新日期: 2023-09-27 18:28:10
错误:
System.Data.dll
中发生类型为System.IndexOutOfRangeException
的未处理异常附加信息:位置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();
}
每当我单击此页面的按钮时,它都会显示异常。我想得到这个名字,但它每次都会给出这个未处理的异常。
如果您连回一行都需要检查!
类似这样的东西:
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();
}
}