-1

I wrote this code to get data from gridview to display down the controls, but it failed:

There is no row at position 0.

at line:

txtSTT.Text = ds.Tables["Trailer"].Rows[0].ItemArray.GetValue(0).ToString();

Full code:

    protected void btnSua_Click(object sender, EventArgs e)
    {
        string STT = ((LinkButton)sender).CommandArgument;

        SqlConnection conn = new SqlConnection(@"Data Source=DESKTOP-R8LG380\SQLEXPRESS;Initial Catalog=PHIM;Integrated Security=True");
        string query = "SELECT * FROM Trailer WHERE STT = '" + STT + "'";
        SqlCommand cmd = new SqlCommand(query, conn);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds, "Trailer");

        txtSTT.Text = ds.Tables["Trailer"].Rows[0].ItemArray.GetValue(0).ToString();
        txtMaTrailer.Text = ds.Tables["Trailer"].Rows[0].ItemArray.GetValue(1).ToString();
        cmbMaPhim.SelectedValue = ds.Tables["Trailer"].Rows[0].ItemArray.GetValue(2).ToString();
        txtUrlTrailer.Text = ds.Tables["Trailer"].Rows[0].ItemArray.GetValue(3).ToString();
        txtGhiChu.Text = ds.Tables["Trailer"].Rows[0].ItemArray.GetValue(4).ToString();

        txtSTT.ReadOnly = true;
        txtSTT.Visible = true;
        lbSTT.Visible = true;
    }
Dale K
  • 25,246
  • 15
  • 42
  • 71
Hoang Dinh
  • 157
  • 1
  • 10
  • What value of STT are you using, and does it definitely exist in your database? – Dale K Apr 16 '19 at 02:06
  • 1
    I would also strongly recommend the use of parameters for passing values to SQL. https://stackoverflow.com/questions/7505808/why-do-we-always-prefer-using-parameters-in-sql-statements – Dale K Apr 16 '19 at 02:06
  • Thanks, Dale, STT exists in my database – Hoang Dinh Apr 16 '19 at 09:06

1 Answers1

0

From the error message, I would say your query is not returning any rows.

Try putting a break point right after the assignment to the queryand copy the string into a query window in SQL Server Management Studio to see if any rows of data come back.

It is probably not returning any rows. Debug your query until you know you have one that returns data.

Also, In addition to putting the contents of this function in a try/catch block, I would wrap all the lines that use ds.Tables["Trailer"].Rows[0] in an if block, something like if(ds.Tables["Trailer"].Rows.Count > 0){

Joseph White
  • 755
  • 5
  • 17
  • No really an answer, more suited to a comment. – Dale K Apr 16 '19 at 02:49
  • @DaleBurrell I have to disagree, there was no clear question, just a stated problem so the implied question is, "How do I fix this?" Explaining how to debug and what to look for and how to avoid the error is too much to fit in a comment. – Joseph White Apr 16 '19 at 02:57
  • Which means you should vote to close the question as its too broad for SO. – Dale K Apr 16 '19 at 02:59