我想在datagridview中編程。我想要的結果是這樣的:當我點擊datagridview(這是combobox列)的第一列時,數據庫中的值應顯示在下一列(textbox列)中。在formload上得到datagridview錯誤:索引超出範圍異常
我得到這個異常:
指數超出範圍。必須是非負
在此行中:
DataGridViewComboBoxCell cb = (DataGridViewComboBoxCell)dataGridView1.Rows[e.RowIndex].Cells[0];
e.RowIndex顯示值-1。
現在我感覺卡在這段代碼中了。可能是什麼問題呢。誰能幫我 ?
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
dataGridView1.CellValueChanged +=
new DataGridViewCellEventHandler(dataGridView1_CellValueChanged);
dataGridView1.CurrentCellDirtyStateChanged +=
new EventHandler(dataGridView1_CurrentCellDirtyStateChanged);
}
private void dataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
if (this.dataGridView1.IsCurrentCellDirty)
{
// This fires the cell value changed handler below
dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
}
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
DataGridViewComboBoxCell cb = (DataGridViewComboBoxCell)dataGridView1.Rows[e.RowIndex].Cells[0];
// ******** e.rowindex shows -1 value.
if (cb.Value != null)
{
con.Open();
SqlCommand cmd = new SqlCommand("select rate FROM Ratemaster where Packagetype = '" + comboBox1.Text +
"' AND Tickettype ='" + ComboboxColumn.Selected + "' ", con);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
dataGridView1.Rows[0].Cells[1].Value = dr[0].ToString();
//dataGridView1.Rows[e.RowIndex].Cells[1].Value = "hi";
}
else
{
//txtRate.Text = "0";
}
con.Close();
}
}
感謝您的建議朋友。但是我沒有得到foo()和bar()的含義。由於我是編程新手,我完全不理解。你能詳細說明你的答案嗎? –
嗨,富和酒吧,特別是連字foobar是任何代碼的常見佔位符,你可以想象。我想表達一下,你應該用你自己的代碼對if子句作出反應,並忽略其他路徑。所以你會這樣做: – kurdy
@ V.Vaibhav很多時候,程序員會用'foo'和'bar'或'foobar'來演示一個例子。上面基本上是說'if(e.RowIndex> = 0)'然後做一些事情 - 其中'foo();'是什麼(不管你想要你的代碼做什麼,然後用它替換'foo()')。代碼的else部分也是如此。 –