如何在C#Windows应用程序中的DataGridView中动态更新/删除? [英] How to update/delete dynamically in DataGridView in C# Windows Application ?

查看:68
本文介绍了如何在C#Windows应用程序中的DataGridView中动态更新/删除?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题是每当我更新任何记录时,它都会在数据库中更新。但是在gridview中它添加了另一条记录而不是更新现有记录。与删除操作相同的问题,记录从数据库中删除但不是从gridview中删除。



我已经搜索过它但没有找到合适的解决方案。



这是代码:

(方法setGroupGridView在每次操作后调用,即插入,更新,删除

& the代码是无错误的,只需要为gridview更新添加一些行。)



主表单

The problem is whenever I update any record, it gets updated in database. But in gridview it adds another record instead of updating the existing one. Same problem with delete operation, record gets deleted from database but not from gridview.

I have searched it already but didn't found proper solution.

Here is the code :
(The method setGroupGridView is called after each operation i.e. insert,update,delete
& the code is error free just need to add some lines for gridview updation.)

Main Form

public partial class frmMain : Form
    {
        Connection cn = new Connection();
        int GId,MId,STId,LId,LTId;
        DataSet ds = new DataSet();
        DataTable dt;

        public frmMain()
        {
            InitializeComponent();
        }

        public frmMain(Form frm)
        {
            InitializeComponent();
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            
            setGroupGridView();

            GId = cn.AutoCodeGen("tblGroupDetails");
            lblGId.Text = GId.ToString();

            //MId = cn.AutoCodeGen("tblMemberDetails");
            //lblMemberId.Text = MId.ToString();


        }

        # region Group Details Code
        //code for inserting record on button click
        private void btnGAdd_Click(object sender, EventArgs e)
        {
            GroupDetails gd=new GroupDetails(lblGId.Text,txtGName.Text);
            gd.Add();
            setGroupGridView();
            resetGroupDetails();
        }
        
        //code for updating record on button click
        private void btnGUpdate_Click(object sender, EventArgs e)
        {
             GroupDetails gd = new GroupDetails(lblGId.Text, txtGName.Text);
             gd.Update();
             setGroupGridView();
             resetGroupDetails();
             btnGUpdate.Enabled = false;
        }

        private void dgvGroupDetails_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 0) //code for setting values in controls on clicking edit image in gridview
            {
                btnGUpdate.Enabled = true;
                lblGId.Text = dgvGroupDetails.Rows[e.RowIndex].Cells[2].Value.ToString();
                txtGName.Text = dgvGroupDetails.Rows[e.RowIndex].Cells[3].Value.ToString();
            }
            else if (e.ColumnIndex == 1)  //code for deleting record on clicking delete image in gridview
            {
                GroupDetails gd = new GroupDetails(dgvGroupDetails.Rows[e.RowIndex].Cells[2].Value.ToString(), dgvGroupDetails.Rows[e.RowIndex].Cells[3].Value.ToString());
                gd.Delete();
                cn.da.Update(dt);
                setGroupGridView();
                resetGroupDetails();
            }
        }

        private void resetGroupDetails()
        {
            GId = cn.AutoCodeGen("tblGroupDetails");
            lblGId.Text = GId.ToString();
            txtGName.Text = "";
        }

        //Binding DataGridview
        private void setGroupGridView()
        {
            
            dt = new DataTable();
            dt = cn.GetDetails("select * from tblGroupDetails");
            dgvGroupDetails.DataSource = dt;
            dgvGroupDetails.ForeColor = Color.Black;
            for (int i = 2; i < dgvGroupDetails.Columns.Count; i++)
            {
                dgvGroupDetails.Columns[i].Width = 150;
            }
        }
        #endregion

    }





Class for insert,update&删除:



Class for insert, update & delete:

class GroupDetails
   {
       protected int GId;
       protected string GName;
       Connection con;

       public GroupDetails(string _GId, string _GName)
       {
           con = new Connection();
           GId = Convert.ToInt16(_GId);
           GName = _GName;
       }

       public void Add()
       {
           con.Execute("insert into tblGroupDetails(GId,GName) values("+ GId +",'"+ GName +"')");
       }

       public void Update()
       {
           con.Execute("update tblGroupDetails set GName='"+ GName +"' where GId=" + GId +"");
       }

       public void Delete()
       {
           con.Execute("delete from tblGroupDetails where GId=" + GId + "");
       }
   }





Class 连接到db:





Class for connection to db:

 public class Connection
    {
        public SqlConnection con;
        public SqlCommand cmd = new SqlCommand();
        public SqlDataAdapter da;
        public DataSet ds = new DataSet();
        public DataTable dt = new DataTable();
        int code;

        public Connection()
        {
            try
            {
                con = new SqlConnection("Data Source=abc;Initial Catalog=db;Integrated Security=True;Pooling=False");
                con.Open();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message, "Connection Failed");
            }
        }

        public void Execute(string query)
        {
            try
            {
                cmd.CommandText = query;
                cmd.Connection = con;
                cmd.ExecuteNonQuery();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message, "Operation Failed.");
            }

        }

        public DataTable GetDetails(string query)
        {
            try
            {
                cmd.CommandText = query;
                cmd.Connection = con;
                da = new SqlDataAdapter(cmd);
                da.Fill(dt);
                return dt;
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message, "Operation Failed.");
                return null;
            }
        }
}





对于解决方案我已尝试过以下代码,但无效对我来说:





For solution I have already tried following code, But works none for me :

//1st solution
dgvGroupDetails.Rows.Clear();

// 2nd solution
If(dgvGroupDetails.DataSource != null)
{
    dgvGroupDetails.DataSource=null;
}
else
{
    dgvGroupDetails.Rows.Clear();
}

推荐答案

只需添加

just add
dt = new DataTable();

到Connection类中的GetDetails方法。

它应该是这样的:



to GetDetails method in Connection class.
and it should be look like this :

public DataTable GetDetails(string query)
       {
           try
           {
               dt = new DataTable();
               cmd.CommandText = query;
               cmd.Connection = con;
               da = new SqlDataAdapter(cmd);
               da.Fill(dt);
               return dt;
           }
           catch (Exception e)
           {
               MessageBox.Show(e.Message, "Operation Failed.");
               return null;
           }
       }







问题出在您正在创建的SetGroupGridView方法中new dataTable但returend Data表是另一个对象。基本上datatable是refrence类型:)你可以改变以下方法




the issue is in SetGroupGridView method you are creating new dataTable but the returend Data table is another object. basically datatable is refrence type :) and you could change the follwoing method

private void SetGroupGridView()
       {

           dt = new DataTable();
           dt = cn.GetDetails("select * from tbl1");
           dgvGroupDetails.DataSource = dt;
           dgvGroupDetails.ForeColor = Color.Black;
           for (int i = 2; i < dgvGroupDetails.Columns.Count; i++)
           {
               dgvGroupDetails.Columns[i].Width = 150;
           }
       }





to





to

private void SetGroupGridView()
{
    dgvGroupDetails.DataSource = cn.GetDetails("select * from tbl1"); ;
    dgvGroupDetails.ForeColor = Color.Black;
    for (int i = 2; i < dgvGroupDetails.Columns.Count; i++)
    {
        dgvGroupDetails.Columns[i].Width = 150;
    }
}


之前我遇到过类似的问题。



我不会向你保证这是最好的解决方案,但考虑使用它来刷新网格中的正确数据。

只需使用这一个:

I had a similar problem before.

I will not assure you this is the best solution, but consider using this to refresh your grid with the correct data.
just use this one:
InitializeComponent();


这篇关于如何在C#Windows应用程序中的DataGridView中动态更新/删除?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆