question

learning-4983 avatar image
0 Votes"
learning-4983 asked DanielZhang-MSFT commented

Thsere is now at position 0

Hi,

     public DataTable getCourseById(int courseID)
     {

         string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
         using(SqlConnection con = new SqlConnection(CS))
         {
             SqlCommand cmd = new SqlCommand("select * from course where id=@courseID", con);
             con.Open();
             cmd.Parameters.AddWithValue("@courseID",courseID);
           
         SqlDataAdapter da = new SqlDataAdapter(cmd);
         DataTable dt = new DataTable();
         da.Fill(dt);
         return dt;
         }

     }


    protected void ddlCourse_SelectedIndexChanged(object sender, EventArgs e)
     {
         int id = Convert.ToInt32(ddlCourse.SelectedValue);

         DataTable dt = new DataTable();

         dt = course.getCourseById(id);

         txtLabel.Text = dt.Rows[0][1].ToString();
         txthours.Text = Convert.ToInt32(dt.Rows[0][2]).ToString();
         txtDesc.Text = dt.Rows[0][3].ToString();
                
     }

As soon as select the course in dropdownlist it is giving me the error saying that there is no row at position 0

Thanks

dotnet-adonet
· 2
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.


It seems that the SELECT statement did not find any row having the specified id. Check the value of the variables and the database content.


0 Votes 0 ·

Hi @learning-4983,
May I know whether your issue has been solved or not? If not, please share it in here. We can work together to figure it out.
Best Regards,
Daniel Zhang

0 Votes 0 ·

1 Answer

DanielZhang-MSFT avatar image
0 Votes"
DanielZhang-MSFT answered DanielZhang-MSFT edited

Hi learning-4983,
You did not check whether your DataTable contains any content. The message indicates that there is no row at position 0.
So you need to verify that rows exist before attempting to get data from them.

 dt = course.getCourseById(id);
     if (dt.Rows.Count > 0)
     {
              txtLabel.Text = dt.Rows[0][1].ToString();
              txthours.Text = Convert.ToInt32(dt.Rows[0][2]).ToString();
              txtDesc.Text = dt.Rows[0][3].ToString();
      } 
     else
     {
         // Handle missing data in an appropriate way...
     }

Best Regards,
Daniel Zhang


If the response is helpful, please click "Accept Answer" and upvote it.

Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.






5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.