-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());
    }
}
4

2 回答 2

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]
于 2013-07-09T12:19:58.100 回答
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) { }
于 2013-07-09T12:23:37.033 回答