删除网格视图行数据错误Windows窗体我的代码附加
本文关键字:我的 窗体 代码 Windows 错误 网格 视图 数据 删除 | 更新日期: 2023-09-27 18:28:32
我正在尝试删除网格视图数据,因为我正在填充类似网格的
public void FillCompanyInfo()
{
DataTable dtCompanyInfo = new DataTable();
dtCompanyInfo = objFunctions.GetCompanyInfo();
if(dtCompanyInfo.Rows.Count>0)
{
dgvCompany.DataSource = dtCompanyInfo;
}
if (dtCompanyInfo.Rows.Count > 0)
{
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);
}
}
}
填充网格后,我点击网格行并点击删除按钮,如
private void btn_Delete_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow r in dgvCompany.Rows)
{
if (Convert.ToBoolean(r.Cells[8].Value)) //cells[4] CONTAINS CHECKBOX COLUMN
{
string strId = r.Cells[1].Value.ToString(); //cells[0] CONTAINS EMPIDCOLUMN
objFunctions.DeleteCompany(strId);
}
}
FillCompanyInfo();
}
但它错误地删除了我的网格视图中的数据,我得到了从0到6的数字和字符串字段,并在第7位添加了chk框,而在将数据绑定到网格后,我还在第8位添加了一列,这可能是由于某种原因吗?
在调试时,我突然注意到在这个地方,
foreach (DataGridViewRow r in dgvCompany.Rows)
该网格视图以这种方式将列chk框放在零位,然后是七个过滤器,然后是chk框在8位,它是如何改变顺序的?
希望您的建议提前感谢
在绑定之前需要清除网格视图数据源。请参阅此链接以清除网格视图。试试这个代码
Datagridview删除所有列
公共void FillCompanyInfo(){
dataGridView1.DataSource = null;
dataGridView1.Columns.Clear();
dtCompanyInfo = GetCompanyInfo();
if (dtCompanyInfo.Rows.Count > 0)
{
dataGridView1.DataSource = dtCompanyInfo;
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''
dataGridView1.Columns.Add(checkColumn);
}
}