2017-07-08 33 views
0

我是初學者,請耐心等待。我有一個錯誤:行集合錯誤

"Additional information: Index was out of range. Must be non-negative and less than the size of the collection."

我想要實現的是點擊我的DataGridView一行並傳遞一個文本框選定行的全部價值。

這裏是我下面的代碼:

月1日,我選擇的「表」的一切,用個MySqlDataAdapter來填補我的數據表。

private void loadrecord() 
    { 
     using (MySqlConnection loadcon = new MySqlConnection(connString)) 
     { 
      loadcon.Open(); 
      MySqlCommand loadcom = new MySqlCommand("SELECT * FROM table1", loadcon); 
      MySqlDataAdapter loadad = new MySqlDataAdapter(loadcom); 
      DataTable loaddt = new DataTable(); 
      loadad.Fill(loaddt); 

      BindingSource loadbindsource = new BindingSource(); 
      loadbindsource.DataSource = loaddt; 
      dataGridView1.DataSource = loadbindsource; 
      loadcon.Close(); 
     } 
    } 

第二,我號召Form1_Load的

private void Form1_Load(object sender, EventArgs e) 
    { 
    loadrecord(); 
    } 

功能loadrecord最後,我有這個dataGridView1

private void dataGridView1_CellContentClick_1(object sender, DataGridViewCellEventArgs e) 
    { 
    //I have 3 records. 1 Balice Book1, 2 Coyman Book2, 3 Pale Book3 
    //Click primarykey on datagridview "1" and pass the value of selected row of "1", pass "1" to Textbox1, pass "Balice" to Textbox2 and pass "Book1" to Textbox3 
    //What I have tried so far is this: 
    Textbox1.Text = dataGridView1.SelectedRows[0].Cells[0].Value.ToString(); 
    Textbox2.Text = dataGridView1.SelectedRows[0].Cells[1].Value.ToString(); 
    Textbox3.Text = dataGridView1.SelectedRows[0].Cells[2].Value.ToString(); 
    //then this error appear whenever I try to click the cells 
    //Additional information: Index was out of range. Must be non-negative and less than the size of the collection. 
    } 

太感謝你了,如果你沒有在此線程的答覆。

回答

0

變化:

Textbox1.Text = dataGridView1.SelectedRows[0].Cells[0].Value.ToString(); 

到:

Textbox1.Text = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString(); 

https://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewcelleventargs(v=vs.110).aspx也有squiz。

+0

先生,我會試試看,看看我是否仍然得到錯誤。非常感謝你 – 19GreenBlankets

+0

實際上它正在工作,但是當我設置單元格[0]時,column_name正在傳遞文本框的值而不是column_id。只是一個簡單的問題先生。我知道它不可能使用-1。是否有可能獲得column_id?我真的想獲得column_id的行值。我的datagridview上只有4列 – 19GreenBlankets

+0

這聽起來像是一個不同的問題?如果是這樣,你可能希望用你的新問題創建一個新的職位。 – mjwills