Reputation: 35
i am trying to delete grid view data as i am filling grid like,
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);
}
}
}
After filling grid i click on grid row and click delete button as,
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();
}
But it delete the data wrongly in my grid view i get fields numeric and string from 0 to 6 and chk box at 7th place while after binding data to grid i also attach one more column at 8 place may me it is due to some that reason ?
while debugging i suddenly notice at this place,
foreach (DataGridViewRow r in dgvCompany.Rows)
that grid view have column in this manner chk box at zero position then seven fild and again then chk box at 8 place how it change the order ?
hopes for your suggestion thanks in advance
Upvotes: 0
Views: 1187
Reputation: 26
You need to clear the grid view data source before bind it.Please Refer this link to clear grid view. try this code
Datagridview remove all columns
public 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);
}
}
Upvotes: 1