-5

Error:

An unhandled exception of type System.IndexOutOfRangeException occurred in System.Data.dll

Additional information: There is no row at position 1.

Code:

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();
 }

Whenever I click the button for this page it shows the exception. I want to get the name this but it gives this unhandled exception every time.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • 4
    what about `Rows[0]` – Daniel A. White Dec 26 '15 at 17:45
  • its the patient id column and i want to get them name of patient by entering the id in textbox 1 – Muhammad Munawar zaman Dec 26 '15 at 17:50
  • [SQL Injection alert](http://msdn.microsoft.com/en-us/library/ms161953%28v=sql.105%29.aspx) - you should **not** concatenate together your SQL statements - use **parametrized queries** instead to avoid SQL injection – marc_s Dec 26 '15 at 17:56
  • As @marc_s stated never let a user provide any part of a SQL statement! See [Bobby Tables](http://imgs.xkcd.com/comics/exploits_of_a_mom.png) – zaph Dec 26 '15 at 18:56

1 Answers1

2

You need to check if you even get back a row!

Something like this:

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();
    }
 }
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459