Click here to Skip to main content
Sign Up to vote bad
good
See more: C#SQLDataGridView
I have a gridview that needs to edit update and delete from datagrid and from my sql server.
 
The problem is with my delete when i run my form and want to delete a row in my datagridview it gives an error index out of range.
 
Here is my form code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
using System.Configuration;
using System.Data.SqlClient;
using System.Windows.Forms.PropertyGridInternal;
 

namespace WindowsFormsApplication1
{
    public partial class Form5 : Form
    {
        SqlConnection con = new SqlConnection(@"Data Source=Admin-PC\SQLEXPRESS;Initial                             Catalog=Couriers;Integrated Security=True");
 
        public Form5()
        {
            InitializeComponent();
            FormBorderStyle = FormBorderStyle.None;
            WindowState = FormWindowState.Maximized;
            TopMost = true;
            Bind();
            
        }
 
        private void Clear()
        {
            textBox1.Text = string.Empty;
            comboBox1.Text = string.Empty;
            textBox7.Text = string.Empty;
            textBox6.Text = string.Empty;
            comboBox2.Text = string.Empty;
            textBox4.Text = string.Empty;
            textBox13.Text = string.Empty;
            textBox2.Text = string.Empty;
            textBox11.Text = string.Empty;
            textBox9.Text = string.Empty;
            textBox14.Text = string.Empty;
        }
        //save
        private void button6_Click(object sender, EventArgs e)
        {
            con.Open();
           SqlCommand cmd = new SqlCommand("Insert Into Waybills set (WaybillNumber,SenderName,SenderAdress,SenderContact,ReceiverName,ReceiverAdress,ReceiverContact,UnitDescription,UnitWeight,Price,Payee) Values (@WaybillNumber,@SenderName,@SenderAdress,@SenderContact,@ReceiverName,@ReceiverAdress,@ReceiverContact,@UnitDescription,@UnitWeight,@Price,@Payee)", con);
           cmd.Parameters.AddWithValue("@WaybillNumber", textBox1.Text);
           cmd.Parameters.AddWithValue("@SenderName", comboBox1.Text);
           cmd.Parameters.AddWithValue("@SenderAddress", textBox7.Text);
           cmd.Parameters.AddWithValue("@SenderContact", textBox7.Text);
           cmd.Parameters.AddWithValue("@ReceiverName", comboBox2.Text);
           cmd.Parameters.AddWithValue("@ReceiverAddress", textBox4.Text);
           cmd.Parameters.AddWithValue("@ReceiverContact", textBox13.Text);
           cmd.Parameters.AddWithValue("@UnitDescription", textBox2.Text);
           cmd.Parameters.AddWithValue("@UnitWeight", textBox11.Text);
           cmd.Parameters.AddWithValue("@Price", textBox9.Text);
           cmd.Parameters.AddWithValue("@Payee", textBox14.Text);
 
           cmd.ExecuteNonQuery();
           con.Close();
           MessageBox.Show("nEW DATA INSERTED");
           Bind();
           Clear();
           dataGridView1.Refresh();
       }
 

        private void Bind()
        {
            con.Open();
            SqlDataAdapter da = new SqlDataAdapter("Select * from Waybills", con);
            DataTable dt = new DataTable();
            da.Fill(dt);
            dataGridView1.DataSource = dt;
            con.Close();
        }
 
       
 
        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
 
        }
 
        private void Form5_Load(object sender, EventArgs e)
        {
            // TODO: This line of code loads data into the 'couriersDataSet2.Waybills' table. You can move, or remove it, as needed.
            this.waybillsTableAdapter1.Fill(this.couriersDataSet2.Waybills);
            
 
        }
        //view data
        private void button1_Click(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection(@"Data Source=Admin-PC\SQLEXPRESS;Initial Catalog=Couriers;Integrated Security=True");
            con.Open();
       
            SqlDataAdapter ad = new SqlDataAdapter("select * from Waybills where WaybillNumber like '%" + textBox5.Text + "%'", con);
            SqlCommandBuilder cb = new SqlCommandBuilder(ad);
            DataSet ds = new DataSet();
            ds.Clear();
            ad.Fill(ds);
            dataGridView1.DataSource = ds.Tables[0];
            if (textBox5.Text == "" || ds.Tables[0].Rows.Count == 0)
            {
                dataGridView1.Visible = false;
            }
            else
            {
                dataGridView1.Visible = true;
                con.Close();
            }
            
        }
 
        private void textBox1_TextChanged(object sender, EventArgs e)
        {
 
        }
 
        private void button2_Click(object sender, EventArgs e)
        {
            Form2 f2 = new Form2();
            f2.ShowDialog();
            this.Close();
        }
 
        private void dataGridView1_CellContentClick_1(object sender, DataGridViewCellEventArgs e)
        {
 
        }
        //edit
        private void button3_Click(object sender, EventArgs e)
        {
            int i;
            i = dataGridView1.SelectedCells[0].RowIndex;
            textBox1.Text = dataGridView1.Rows[i].Cells[0].Value.ToString();
            comboBox1.Text = dataGridView1.Rows[i].Cells[1].Value.ToString();
            textBox7.Text = dataGridView1.Rows[i].Cells[2].Value.ToString();
            textBox6.Text = dataGridView1.Rows[i].Cells[3].Value.ToString();
            comboBox2.Text = dataGridView1.Rows[i].Cells[4].Value.ToString();
            textBox4.Text = dataGridView1.Rows[i].Cells[5].Value.ToString();
            textBox13.Text = dataGridView1.Rows[i].Cells[6].Value.ToString();
            textBox2.Text = dataGridView1.Rows[i].Cells[7].Value.ToString();
            textBox11.Text = dataGridView1.Rows[i].Cells[8].Value.ToString();
            textBox9.Text = dataGridView1.Rows[i].Cells[9].Value.ToString();
            textBox14.Text = dataGridView1.Rows[i].Cells[10].Value.ToString();
        }
        //delete rows
        private void button4_Click(object sender, EventArgs e)
        {
            SqlCommand delcmd = new SqlCommand();
            if (dataGridView1.Rows.Count > 1 && dataGridView1.SelectedRows[0].Index != dataGridView1.Rows.Count - 1)
            {
                delcmd.CommandText = " DELETE FROM Waybills WHERE WaybillNumber=" + dataGridView1.SelectedRows[0].Cells[0].Value.ToString() + "";
                con.Open();
                delcmd.Connection = con;
                delcmd.ExecuteNonQuery();
                con.Close();
                dataGridView1.Rows.RemoveAt(dataGridView1.SelectedRows[0].Index);
                MessageBox.Show("Waybill Deleted");
            }
            Bind();
 
        }
        //update
        private void button5_Click(object sender, EventArgs e)
        {
            con.Open();
            SqlCommand cmd = new SqlCommand("UPDATE Waybills set WaybillNumber = @WaybillNumber, SenderName = @SenderName, SenderAddress = @SenderAddress, SenderContact = @SenderContact, ReceiverName = @ReceiverName, ReceiverAddress = @ReceiverAddress, ReceiverContact = @ReceiverContact, UnitDescription = @UnitDescription, UnitWeight = @UnitWeight, Price = @Price, Payee = @Payee Where(WaybillNumber=@WaybillNumber)", con);
 
            cmd.Parameters.AddWithValue("@WaybillNumber", textBox1.Text);
            cmd.Parameters.AddWithValue("@SenderName", comboBox1.Text);
            cmd.Parameters.AddWithValue("@SenderAddress", textBox7.Text);
            cmd.Parameters.AddWithValue("@SenderContact", textBox7.Text);
            cmd.Parameters.AddWithValue("@ReceiverName", comboBox2.Text);
            cmd.Parameters.AddWithValue("@ReceiverAddress", textBox4.Text);
            cmd.Parameters.AddWithValue("@ReceiverContact", textBox13.Text);
            cmd.Parameters.AddWithValue("@UnitDescription", textBox2.Text);
            cmd.Parameters.AddWithValue("@UnitWeight", textBox11.Text);
            cmd.Parameters.AddWithValue("@Price", textBox9.Text);
            cmd.Parameters.AddWithValue("@Payee", textBox14.Text);
            
            cmd.ExecuteNonQuery();
            MessageBox.Show("updated");
            con.Close();
            Bind();
            Clear();
        }
 
    }
}
 
Can someone tell me where my problem is
Posted 6 Sep '12 - 20:18
Edited 6 Sep '12 - 20:27


3 solutions

Check selected row not eqal to -1
private void button4_Click(object sender, EventArgs e)
       {
if(dataGridView1.SelectedRows[0].Index != -1)
 {
           SqlCommand delcmd = new SqlCommand();
           if (dataGridView1.Rows.Count > 1 && dataGridView1.SelectedRows[0].Index != dataGridView1.Rows.Count - 1)
           {
               delcmd.CommandText = " DELETE FROM Waybills WHERE WaybillNumber=" + dataGridView1.SelectedRows[0].Cells[0].Value.ToString() + "";
               con.Open();
               delcmd.Connection = con;
               delcmd.ExecuteNonQuery();
               con.Close();
               dataGridView1.Rows.RemoveAt(dataGridView1.SelectedRows[0].Index);
               MessageBox.Show("Waybill Deleted");
           }
           Bind();
    }
 
 }
  Permalink  
Comments
GoggatjieLiesl - 11 Sep '12 - 7:28
Thanks its working
pradiprenushe - 11 Sep '12 - 7:45
Welcome
The problem is in this line..
if (dataGridView1.Rows.Count > 1 && dataGridView1.SelectedRows[0].Index != dataGridView1.Rows.Count - 1)
try with..
if (dataGridView1.Rows.Count >= 1 && dataGridView1.SelectedRows[0].Index == dataGridView1.Rows.Count - 1)
  Permalink  
Comments
GoggatjieLiesl - 7 Sep '12 - 2:36
Thank you very much for the quick answer back
GoggatjieLiesl - 11 Sep '12 - 5:41
Hey i tried changing my code to if (dataGridView1.Rows.Count >= 1 && dataGridView1.SelectedRows[0].Index == dataGridView1.Rows.Count - 1) now the program just keeps on running when i press delete button, it doesnt even want to exit application. please help
Hey i tried changing my code to if (dataGridView1.Rows.Count >= 1 && dataGridView1.SelectedRows[0].Index == dataGridView1.Rows.Count - 1) now the program just keeps on running when i press delete button, it doesnt even want to exit application. please help
  Permalink  

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Your Filters
Interested
Ignored
     
0 Sergey Alexandrovich Kryukov 425
1 OriginalGriff 315
2 Slacker007 240
3 Aarti Meswania 210
4 Maciej Los 200
0 Sergey Alexandrovich Kryukov 8,953
1 OriginalGriff 7,134
2 CPallini 3,758
3 Rohan Leuva 3,036
4 Maciej Los 2,488


Advertise | Privacy | Mobile
Web04 | 2.6.130516.1 | Last Updated 11 Sep 2012
Copyright © CodeProject, 1999-2013
All Rights Reserved. Terms of Use
Layout: fixed | fluid