junaid khurshid

junaid khurshid

  • NA
  • 52
  • 6.7k

Index Out of Range in datagrid at data deletion or updation.

Jul 2 2014 1:27 PM
I got exception on deletion of data in datagrid .
My xaml code is this for data grid:
<DataGrid AutoGenerateColumns="false" Height="341" HorizontalAlignment="Left" IsReadOnly="True" Margin="10,98,0,0" Name="dataGrid1" VerticalAlignment="Top" Width="298" SelectionChanged="dataGrid1_SelectionChanged" Grid.ColumnSpan="2" Visibility="{Binding}">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding commanNameId}" Header="CommanNameId" ></DataGridTextColumn>
<DataGridTextColumn Binding="{Binding commanName}" Header="CommanName"></DataGridTextColumn>
<DataGridTextColumn Binding="{Binding date}" Header="Date" ></DataGridTextColumn>

</DataGrid.Columns>
</DataGrid>
My grid load function is this:
 
 private void grid_load()
{
try
{
con.Open();
string CmdString = string.Empty;
SqlDataReader rd;
SqlCommand cmod = new SqlCommand("Select catageoryId from catageory where catageoryName='" + textBlock2.Text + "'", con);
rd = cmod.ExecuteReader();
if (rd.Read())
{
idlbl.Text = rd[0].ToString();
rd.Close();
CmdString = "Select commanNameId, commanName ,date from commanNametbl ";
SqlCommand cmd = new SqlCommand(CmdString, con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable("Tables");
sda.Fill(dt);

dataGrid1.ItemsSource = dt.DefaultView;
con.Close();
//MessageBox.Show(ex.ToString());
}
else
{
rd.Close();
}
}
catch (Exception ex) {
MessageBox.Show(ex.Message);
}
}
 My delete button code is this:
 private void delbtn_Click(object sender, RoutedEventArgs e)
{

try
{
string message = "Are you sure?";
string caption = "Confirmation";
MessageBoxButton buttons = MessageBoxButton.YesNo;
MessageBoxImage icon = MessageBoxImage.Question;

if (MessageBox.Show(message, caption, buttons, icon) == MessageBoxResult.Yes)
{

if (dataGrid1.SelectedValue != null)
{
con.Open();
SqlCommand ccmd = new SqlCommand("Select Count(*) from productionStock where commanNameId='" + comBlock.Text + "'", con);
Int32 count = (Int32)ccmd.ExecuteScalar();
con.Close();
if (count > 0)
{
MessageBox.Show("This CommanName is assigned to Plants Stock");
}
else
{
con.Open();
SqlCommand cmd = new SqlCommand("Delete from commanNametbl where commanNameId='" + comBlock.Text + "'", con);
cmd.ExecuteNonQuery();
con.Close();
comanNametextBox.Text = "";
comNametextBlock.Text = "";
MessageBox.Show("Record Deleted Sucessfully!");
grid_load();
}

}
else
{
MessageBox.Show("Select values from Table");
}
}
else
{

}

}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
I have got exception when i click the delete Btn ..actually when grid id reload then it gives exception

Answers (16)