希望有人可以帮助解决这个问题。我的代码中有一个我无法解决的错误。我正在测试使用DataGridView控件的选择索引事件处理。
我创建了两列: -
第0列是DataGridViewTextBoxColum
第1列是DataGridViewComboBoxColumn
我已经为我的ComboBox
列提供了一个数据源,这是一个很小的DataTable
,包含两个Username
&列。 UserID
。
显示成员设置为用户名列,我将UserID列设置为ValueMember。
我要做的就是第0列(DataGridViewTextBox
),在UserID
的Index Changed事件中使用ValueMember
(DataGridViewComboBoxColumn
)填充。< / p>
首次加载程序时,它工作正常。 IndexChanged
事件触发没有任何错误。但是如果我尝试在新行中选择ComboBox
,它将清除前一行中的组合框中的值,然后抛出一个空引用异常。
我已经列出了下面的代码并突出显示了它失败的代码行: -
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
LoadData();
}
public OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Documents and Settings\riversd\Desktop\Test.accdb");
public string sql = "SELECT * FROM [AgentList]";
private void LoadData()
{
dataGridView1.EditMode = DataGridViewEditMode.EditOnEnter;
DataTable dt = AgentTable(sql, con);
DataGridViewTextBoxColumn textbox = new DataGridViewTextBoxColumn();
dataGridView1.Columns.Add(textbox);
DataGridViewComboBoxColumn combo = new DataGridViewComboBoxColumn();
combo.DataSource = dt;
combo.DisplayMember = "agentName";
combo.ValueMember = "AgentID";
dataGridView1.Columns.Add(combo);
}
public DataTable AgentTable(string SQL, OleDbConnection con)
{
var AgentList = new DataTable();
var SELECTcommand = new OleDbCommand(SQL, con);
var adaptor = new OleDbDataAdapter();
adaptor.SelectCommand = SELECTcommand;
con.Open();
adaptor.SelectCommand.ExecuteNonQuery();
adaptor.Fill(AgentList);
con.Close();
return AgentList;
}
private void dataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
DataGridViewColumn col = dataGridView1.Columns[dataGridView1.CurrentCell.ColumnIndex];
if (col is DataGridViewComboBoxColumn)
{
dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
}
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if (dataGridView1.CurrentCell.ColumnIndex == 1 && e.Control is ComboBox)
{
ComboBox comboBox = e.Control as ComboBox;
comboBox.SelectedIndexChanged += LastColumnComboSelectionChanged;
}
}
private void LastColumnComboSelectionChanged(object sender, EventArgs e)
{
var currentcell = dataGridView1.CurrentCellAddress;
var sendingCB = sender as DataGridViewComboBoxEditingControl;
DataGridViewTextBoxCell cel = (DataGridViewTextBoxCell)dataGridView1.Rows[currentcell.Y].Cells[0];
// HERE IS THE LINE THAT THROES EXCEPTION WHEN MOVING FROM
// ONE COMBOXCELL to another.
cel.Value = sendingCB.SelectedValue.ToString();
}
}
答案 0 :(得分:1)
尝试换行: -
DataGridViewTextBoxCell cel = (DataGridViewTextBoxCell)dataGridView1.Rows[currentcell.Y].Cells[0];
到
DataGridViewTextBoxCell cel = (DataGridViewTextBoxCell)dataGridView1.Rows[currentcell.Y].Cells[1];