错误:
中发生了
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();
}
每当我点击此页面的按钮时,它都会显示异常。我希望得到这个名字,但它每次都会给出这个未处理的例外。
答案 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();
}
}