填充网格视图,然后在单元格上单击我在单元格单击事件上填充文本框,例如,
private void dgvCompany_CellClick(object sender, DataGridViewCellEventArgs e)
{
int i = dgvCompany.SelectedCells[0].RowIndex;
ID = dgvCompany.Rows[i].Cells[0].Value.ToString();
txtCompanyName.Text = dgvCompany.Rows[i].Cells[1].Value.ToString();
txtContactName.Text = dgvCompany.Rows[i].Cells[2].Value.ToString();
txtContactPersonPhone.Text = dgvCompany.Rows[i].Cells[3].Value.ToString();
txtAddress.Text = dgvCompany.Rows[i].Cells[4].Value.ToString();
txtCity.Text = dgvCompany.Rows[i].Cells[5].Value.ToString();
txtPhone.Text = dgvCompany.Rows[i].Cells[6].Value.ToString();
cbIsActive.Checked = Convert.ToBoolean(dgvCompany.Rows[i].Cells[7].Value);
}
这里 ID 是填充文本框后的字符串变量,我编辑并保存更新,然后像以前的方法一样重新填充网格,
public void FillCompanyInfo()
{
DataTable dtCompanyInfo = objFunctions.GetCompanyInfo();
if(dtCompanyInfo.Rows.Count>0)
{
dgvCompany.DataSource = dtCompanyInfo;
if (this.dgvCompany.Columns.Count == 8)
{
DataGridViewCheckBoxColumn checkColumn = new DataGridViewCheckBoxColumn();
checkColumn.Name = "";
checkColumn.HeaderText = "Select";
checkColumn.Width = 50;
checkColumn.ReadOnly = false;
checkColumn.FillWeight = 10; //if the datagridview is resized (on form resize) the checkbox won't take up too much; value is relative to the other columns' fill values\\
dgvCompany.Columns.Add(checkColumn);
}
}
}
在这里,我使用 if 条件将列计数为 8,因为每次它添加列 Select 并在我单击网格和单元格单击事件触发后再次填充网格后导致错误,
在线的 ,
ID = dgvCompany.Rows[i].Cells[0].Value.ToString();
找不到对象引用,因为它在单元格 0 上为空,而在单元格单击更新之前它工作正常,当我使用断点时,我在单元格 [1] 上获取 ID,而单元格 [0] 为空
我不理解这个错误
希望你的建议
谢谢