2013-07-09 58 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

相关问题