我在StackOverflow和整个互联网上浏览了很多但却找不到任何可以帮助我的东西。我将一些SQL数据库中的信息放到DataGridView上,我正在添加一个带复选框的额外列。
private void populatedataGrid()
{
String sql = "SELECT pm.Name, pm.telephone, pm.email, pm.validID, comp.name as `Company` FROM `project managers`as pm JOIN `companies`as comp ON pm.Companies_companyID = comp.companyID where pm.Companies_companyID =" + loginID;
MySqlCommand command = new MySqlCommand(sql, dh.Connection);
try
{
MySqlDataAdapter adapter = new MySqlDataAdapter();
adapter.SelectCommand = command;
DataTable dbdataset = new DataTable();
adapter.Fill(dbdataset);
BindingSource bSource = new BindingSource();
// DataGridView1 is a different DataGrid, i am working on DataGridView2
bSource.DataSource = dbdataset;
dataGridView1.DataSource = bSource;
dataGridView2.DataSource = bSource;
//Method for adding the additional column with checkboxes (ill paste the method below)
addCheckBoxColumn();
//I make it so that only the checkboxes can be edited
foreach (DataGridViewColumn dc in dataGridView2.Columns)
{
if (dc.Index.Equals(5))
{
dc.ReadOnly = false;
}
else
{
dc.ReadOnly = true;
}
}
adapter.Update(dbdataset);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
dh.Connection.Close();
}
}
以下是使用Checkboxes创建列的方法:
private void addCheckBoxColumn()
{
DataGridViewCheckBoxColumn cbCol = new DataGridViewCheckBoxColumn();
cbCol.ValueType = typeof(bool);
cbCol.Name = "Select";
cbCol.HeaderText = "Select";
dataGridView2.Columns.Add(cbCol);
}
现在一切正常:
我创建了一个用于测试目的的按钮,我想在单击时在label2上写入要检查的复选框的名称。所以这就是我写的方法:
private void button1_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in dataGridView2.Rows)
{
DataGridViewCheckBoxCell cbxcell = row.Cells[5] as DataGridViewCheckBoxCell;
if ((bool)cbxcell.Value == true)
{
label2.Text = row.Cells[1].Value.ToString();
}
}
}
当我运行它并单击Button1时,我得到以下异常: “BuildID-Company-Backend.exe中发生了'System.NullReferenceException'类型的未处理异常
附加信息:对象引用未设置为对象的实例。“
有什么想法吗? :(