Thsere is now at position 0

learning 1 Reputation point
2021-06-07T20:34:53.843+00:00

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

.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,353 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Daniel Zhang-MSFT 9,611 Reputation points
    2021-06-08T01:46:30.507+00:00

    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.

    0 comments No comments