2013-07-09 93 views
-2
private void dataGridView1_DoubleClick(object sender, EventArgs e) 
{ 
    try 
    { 
     DataTable dt = new DataTable(); 

     // In database there are three columns: proid, proname, and unitprice. 
     // I need this to retrieve in respective textbox when i double click 
     // the value in datagrid view 
     SqlDataAdapter da = new SqlDataAdapter(" select * from tblproduct where proid = " + 
      Convert.ToInt16(dataGridView1.SelectedRows[0].Cells[0].Value.ToString()) + "", con); 
     // Something wrong near this select statement so getting error index was out of range. 
     da.Fill(dt); 
     textBox1.Text = dt.Rows[0][0].ToString(); 
     textBox2.Text = dt.Rows[0][1].ToString(); 
     textBox3.Text = dt.Rows[0][2].ToString(); 
    } 
    catch (Exception error) 
    { 
     MessageBox.Show(error.ToString()); 
    } 
} 
+0

在哪一行..? –

+3

你至少應該給關於您的問題一個句子,不只是將代碼粘貼 – Jonesopolis

+1

嘗試'Convert.ToInt32(...' – mcalex

回答

5

這隻能在四個不同的線路發生:

// either SelectedRows or Cells is zero length 
dataGridView1.SelectedRows[0].Cells[0] 

// either Rows is zero length or there are no columns returned 
dt.Rows[0][0] 

// either Rows is zero length or there is only 1 column returned 
dt.Rows[0][1] 

// either Rows is zero length or there are only 2 columns returned 
dt.Rows[0][2] 

最有可能的線路?

// there are no SelectedRows 
dataGridView1.SelectedRows[0].Cells[0] 

// there are no Rows returned 
dt.Rows[0][0] 
0

如果SqlDataAdapter的就像是我用過的其他適配器,您需要先建立連接,它從你給的代碼示例我們不會出現你在幹什麼。您可能需要嘗試如下所示:

SqlConnection connex = new SqlConnection(); 
connex.ConnnectionString = "connection string to data"; 

try 
{ 
    //connect to the database 
    connex.Open(); 
    //set the select command to be used for pulling in info 
    da.SelectCommand.Connection = connex; 
    //fill the dbData object with data from the database 
    da.Fill(dt); 
    //close database connection 
    connex.Close(); 
} 
catch (Exception ex) { } 
+0

我相信「con」在連接中的SqlDataAdapter –

+0

我已經聲明連接字符串全局先生 – pooja

相關問題