Datagridview更新和删除

Datagridview更新和删除

本文介绍了C#Datagridview更新和删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个gridview,需要编辑更新和从datagrid和我的sql服务器中删除.

问题出在我运行表单并想在datagridview中删除一行时删除了它,从而导致错误索引超出范围.

这是我的表格代码

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

推荐答案

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();
    }

 }


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)



这篇关于C#Datagridview更新和删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 19:30