Index was out of range. Must be non-negative and less than the size of the collection

  • Thread starter Thread starter Urgen Kalsang
  • Start date Start date
U

Urgen Kalsang

Guest
Following is my code snippet to remove selected row from the datagridview.

I dont know, where m i doing wrong, getting an error : "Index was out of range. Must be non-negative and less than the size of the collection"


private void button1_Click(object sender, EventArgs e)
{
if (cnn.State == ConnectionState.Open )
{
cnn.Close();
}
else
{
cnn.Open();
string sql = "Select * from Login_Mast";
SqlCommand scommand = new SqlCommand(sql, cnn);
SqlDataAdapter sAdapter = new SqlDataAdapter(scommand);
SqlCommandBuilder sBuilder = new SqlCommandBuilder(sAdapter);
DataSet sDS = new DataSet();
DataTable sTable;
sAdapter.Fill(sDS, "Login_Mast");
sTable = sDS.Tables["Login_Maast"];
cnn.Close();
dataGridView1.DataSource = sDS.Tables["Login_Mast"];
dataGridView1.ReadOnly = true;
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;

if(MessageBox.Show ("Do you want to delete this record ?", "Delete", MessageBoxButtons.YesNo)==DialogResult.Yes )
{
dataGridView1.Rows.RemoveAt(dataGridView1.SelectedRows[0].Index);
sAdapter.Update(sTable);
}

MessageBox.Show ("Record deleted successfully");



}
}

Continue reading...
 
Back
Top