2017-06-01 36 views
-1

我收到這個sql錯誤,在位置-1處沒有行。沒有位置的行-1

這就是我所做的。

void showData(int index) 
    { 

     Connection con = new OrderManager.Connection(); 
     SqlDataAdapter sda = new SqlDataAdapter("Select * from [MasterDatabase].[dbo].[Neworder] Where OrderID = '" + TxtBox_OrderID.Text + "'", con.ActiveCon()); 

     dt = new DataTable(); 
     sda.Fill(dt); 

     TxtBox_OrderID.Text = dt.Rows[index][0].ToString(); 
     ClearTextBoxes(); 
     dataGridView1.Rows.Clear(); 
     foreach (DataRow item in dt.Rows) 
     { 
      int n = dataGridView1.Rows.Add(); 

      dataGridView1.Rows[n].Cells[0].Value = item["OrderID"].ToString(); 
      dataGridView1.Rows[n].Cells[1].Value = item["Date"].ToString(); 
      dataGridView1.Rows[n].Cells[2].Value = item["Customer_Name"].ToString(); 
      dataGridView1.Rows[n].Cells[3].Value = item["ProductID"].ToString(); 
      dataGridView1.Rows[n].Cells[4].Value = item["Product_Name"].ToString(); 
      dataGridView1.Rows[n].Cells[5].Value = item["Product_Color"].ToString(); 
      dataGridView1.Rows[n].Cells[6].Value = item["Product_PCs"].ToString(); 
      dataGridView1.Rows[n].Cells[7].Value = item["Product_Cutting"].ToString(); 
      dataGridView1.Rows[n].Cells[8].Value = item["Product_TotalYards"].ToString(); 
     } 
     label12.Text = "Row Count: " + dt.Rows.Count.ToString(); 

    } 

我想在導航其OrderID等於數據庫中的訂單ID時僅顯示那些記錄。

+0

爲什麼你不只是設置網格的數據源屬性與您的表(並選擇只需要在網格中的字段)? – Steve

+0

但是,由於您的某個DataRow字段名稱拼寫錯誤,因此發生此錯誤。檢查它們 – Steve

+0

綁定到*的dataGridView1 * *是什麼?這是一個什麼樣的視角*超過*?它可能*不能添加*。例如,是否有數據源? –

回答

0

我覺得在這一行

TxtBox_OrderID.Text = dt.Rows[index][0].ToString(); 

,這不是一個SQL錯誤,但一個簡單的索引超出數組的邊界發生的錯誤。
由於某些原因,當您嘗試使用未包含在DataTable的Rows集合中的行時,您會收到此錯誤消息,而不是較不明確的IndexOutOfRangeException。如果您爲小於零或大於數據表dt中的行數的索引變量傳遞某個值,則會出現此消息。
您不必對查詢返回的行數的任何檢查,因此有可能是您的查詢不返回任何記錄或索引的簡單值爲-1

void showData(int index) 
{ 

    Connection con = new OrderManager.Connection(); 
    SqlDataAdapter sda = new SqlDataAdapter(".......", con.ActiveCon()); 
    dt = new DataTable(); 
    sda.Fill(dt); 

    // Protect the access to the rows collection of the table... 
    if(index < dt.RowsCount && index >= 0) 
    { 
     TxtBox_OrderID.Text = dt.Rows[index][0].ToString(); 
     // the code that fills the datagrid 
    } 
    else 
    { 
     // Message for your user about a record not found 
    } 
} 

作爲一個邊請注意,請儘快按照parameterize your query給出的建議。你將避免Sql Injection和parsin問題

+0

這個查詢'SqlDataAdapter sda = new SqlDataAdapter(「Select * from Neworder」,con.ActiveCon());'顯示給我這個 http://i63.tinypic.com/imts7d.jpg – Patrick

+0

和這個查詢'SqlDataAdapter sda = new SqlDataAdapter(「Select * from [MasterDatabase]。[dbo]。[Neworder] Where OrderID ='」+ TxtBox_OrderID.Text +「'」,con.ActiveCon());'顯示我這個錯誤http:// i63 .tinypic.com/szcxm1.jpg 在導航給我這個:http://i68.tinypic.com/jv3dra.jpg – Patrick

+0

'private void btn_NextRecord_Click(object sender,EventArgs e) { pos ++; if(pos Patrick