h1.post-title { color:orange; font-family:verdana,Arial; font-weight:bold; padding-bottom:5px; text-shadow:#64665b 0px 1px 1px; font-size:32px; } -->

Pages

Add or Remove Datagridview in C#.Net

    Today, we discussed "Add or Remove Datagridview in C#.Net"

public void AddorRemoveRows(DataGridView DGV, CheckedListBox chk, string Mode)
{
try
{
switch (Mode)
{
case "Add":
if (chk.SelectedItem.ToString() != null)
{
string SelectedItem = chk.SelectedItem.ToString();
DGV.RowCount = DGV.RowCount + 1;
DGV.Rows[DGV.RowCount - 1].Cells[0].Value = SelectedItem;
chk.SelectedIndex = -1;
}
break;
case "Remove":
string UnSelectedItem = chk.SelectedItem.ToString();
int SelectedIndex = RowId(UnSelectedItem, DGV);
DGV.Rows.RemoveAt(SelectedIndex);
break;
}
}
catch (Exception ex)
{
Program.WriteLog(ex.Message, ex.StackTrace);
}
}
RowId Method
int rowId;
private int RowId(string unSelectedItem, DataGridView dgv)
{
for (int rowidx = 0; rowidx < dgv.Rows.Count; rowidx++)
{
if (unSelectedItem == Convert.ToString(dgv.Rows[rowidx].Cells[0].Value))
{
rowId = rowidx;
break;
}
}
return rowId;
}