C#使用更新和删除功能从数据库中填充GridView

时间:2014-05-21 07:29:09

标签: c# sql winforms datagridview

我一直在寻找一种方法,使用编辑和删除功能从sql本地数据库填充GridView,而不会产生重复。

到目前为止,我已经创建了一个SQL查询,将结果存储为数据表并将其输入GridView。我似乎无法弄清楚如何管理编辑和删除功能,并希望有人可以提供帮助。

非常感谢。

以下是我填充GridView的方法:

//Load data in to parameters gridview
        using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["PowerShellManager.Properties.Settings.PSManagerConnectionString"].ConnectionString))
        {
            con.Open();

            SqlCommand comm3 = new SqlCommand("SELECT * FROM Parameters WHERE ScriptId = (SELECT Scripts.ScriptId FROM Scripts WHERE Scripts.ScriptName = @ScriptName) AND ProfileId = (SELECT Profiles.ProfileId FROM Profiles WHERE Profiles.ProfileName = @currentlySelectedProfile)", con);
            comm3.Parameters.AddWithValue("ScriptName", listView_Scripts.SelectedItems[0].Text);
            comm3.Parameters.AddWithValue("currentlySelectedProfile", currentlySelectedProfile);
            DataTable t3 = new DataTable();
            t3.Load(comm3.ExecuteReader());
            //variablesDataGridView.DataSource = null;
            parametersDataGridView.DataSource = t3;
            //variablesBindingSource.Filter = new 
            con.Close();
        }

3 个答案:

答案 0 :(得分:4)

我为您创建了一个简单的应用程序并编辑了整个答案!这将是一个很长的答案。您可以将新Person保存到数据库或从数据库中删除Person,以及GridView。这是带有一些图片示例的代码:

人员类:

public class Person
{

    #region Members

    private int _ID = -1;
    private string _FirstName = string.Empty;
    private string _LastName = string.Empty;
    private DateTime? _BirthDate = null;
    private string _PhoneNumber = string.Empty;
    private string _Email = string.Empty;
    private bool _Changed = false;

    #endregion

    public Person()
    {
        _Changed = false;
    }

    #region Methods

    public void Save()
    {
        if (!_Changed)
            return;

        using (SqlConnection con = new SqlConnection(@"server=.\sqlexpress;database=People;integrated Security=True;"))
        {
            SqlCommand cmd = con.CreateCommand();
            cmd.CommandText = "Person_Save";
            cmd.CommandType = System.Data.CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@ID", _ID);
            cmd.Parameters.AddWithValue("@FirstName", _FirstName);
            cmd.Parameters.AddWithValue("@LastName", _LastName);
            cmd.Parameters.AddWithValue("@BirthDate", _BirthDate);
            cmd.Parameters.AddWithValue("@PhoneNumber", _PhoneNumber);
            cmd.Parameters.AddWithValue("@Email", _Email);

            try
            {
                con.Open();

                using (SqlDataReader dr = cmd.ExecuteReader())
                {
                    if (dr.Read())
                    {
                        _ID = dr.GetInt32(0);
                        _Changed = false;
                    }
                }
            }
            catch (SqlException ex)
            {
                MessageBox.Show(ex.Message, "Error message");
            }
        }
    }

    public void Delete()
    {
        using (SqlConnection con = new SqlConnection(@"server=.\sqlexpress;database=People;integrated Security=True;"))
        {
            SqlCommand cmd = con.CreateCommand();
            cmd.CommandText = "Person_Delete";
            cmd.CommandType = System.Data.CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@ID", _ID);

            try
            {
                con.Open();
                cmd.ExecuteNonQuery();
            }
            catch (SqlException ex)
            {
                MessageBox.Show(ex.Message, "Error message");
            }
        }
    }

    #endregion

    #region Properties

    public int ID
    {
        get { return _ID; }
        set
        {
            if (_ID != value)
            {
                _ID = value;
                _Changed = true;
            }
        }
    }

    public string FirstName
    {
        get { return _FirstName; }
        set
        {
            if (_FirstName != value)
            {
                _FirstName = value;
                _Changed = true;
            }
        }
    }

    public string LastName
    {
        get { return _LastName; }
        set
        {
            if (_LastName != value)
            {
                _LastName = value;
                _Changed = true;
            }
        }
    }

    public DateTime? BirthDate
    {
        get { return _BirthDate; }
        set
        {
            if (_BirthDate != value)
            {
                _BirthDate = value;
                _Changed = true;
            }
        }
    }

    public string PhoneNumber
    {
        get { return _PhoneNumber; }
        set
        {
            if (_PhoneNumber != value)
            {
                _PhoneNumber = value;
                _Changed = true;
            }
        }
    }

    public string Email
    {
        get { return _Email; }
        set
        {
            if (_Email != value)
            {
                _Email = value;
                _Changed = true;
            }
        }
    }

    public bool Changed
    {
        get { return _Changed; }
        set { _Changed = value; }
    }

    #endregion

}

PeopleForm类:

public partial class PeopleForm : Form
{
    public PeopleForm()
    {
        InitializeComponent();

        FillDataSource();
    }

    public void FillDataSource()
    {
        List<Person> list = new List<Person>();

        using (SqlConnection con = new SqlConnection(@"server=.\sqlexpress;database=People;integrated Security=True;"))
        {
            SqlCommand cmd = con.CreateCommand();
            cmd.CommandText = "People_Read";
            cmd.CommandType = System.Data.CommandType.StoredProcedure;

            try
            {
                con.Open();

                using (SqlDataReader dr = cmd.ExecuteReader())
                {
                    while (dr.Read())
                    {
                        list.Add(new Person()
                        {
                            ID = (int)dr["ID"]
                           ,FirstName = dr["FirstName"] as string
                           ,LastName = dr["LastName"] as string
                           ,BirthDate = dr["BirthDate"] as DateTime?
                           ,PhoneNumber = dr["PhoneNumber"] as string
                           ,Email = dr["Email"] as string
                        });
                    }
                }
            }
            catch (SqlException ex)
            {
                MessageBox.Show(ex.Message, "Error message");
            }
        }

        personBindingSource.DataSource = list;
    }

    private void btnSave_Click(object sender, EventArgs e)
    {
        foreach (Person person in personBindingSource)
        {
            person.Save();
        }
    }

    private void btnDelete_Click(object sender, EventArgs e)
    {
        ((Person)grdPeople.CurrentRow.DataBoundItem).Delete();
        personBindingSource.RemoveAt(grdPeople.CurrentRow.Index);
    }
}

存储过程:

CREATE PROCEDURE [dbo].[Person_Save]
     @ID int
    ,@FirstName nvarchar(30)
    ,@LastName nvarchar(30)
    ,@BirthDate date
    ,@PhoneNumber nvarchar(30)
    ,@Email nvarchar(50)
AS
BEGIN
    IF(@ID = -1)
    BEGIN
        INSERT INTO People
        VALUES (@FirstName,
                @LastName,
                @BirthDate,
                @PhoneNumber,
                @Email)

        SET @ID = SCOPE_IDENTITY();
    END
    ELSE
    BEGIN
        UPDATE  People
        SET     FirstName = @FirstName,
                LastName = @LastName,
                BirthDate = @BirthDate,
                PhoneNumber = @PhoneNumber,
                Email = @Email

        WHERE   ID = @ID
    END

    SELECT @ID;     
END

CREATE PROCEDURE [dbo].[Person_Delete]
    @ID int
AS
BEGIN
    DELETE
    FROM People
    WHERE ID = @ID
END

CREATE PROCEDURE [dbo].[People_Read]
AS
BEGIN
    SELECT   ID
            ,FirstName
            ,LastName
            ,BirthDate
            ,PhoneNumber
            ,Email
    FROM People
    ORDER BY LastName, FirstName        
END

您必须将Person类绑定到DataGridView作为绑定源,如下所示:

Binding step 1 Binding step 2

最后,您将获得如下所示的工作应用程序:

Complete application

请注意,我稍微改变了颜色,没什么特别的。我添加了一些人作为例子。您必须在出生日期列中处理错误输入的错误,但要有一些有趣的探索。我想我给你的慷慨开始你的申请。

玩得开心!

答案 1 :(得分:0)

如果您是C#/ ASP.net的新手 - 为此,我建议先阅读一本书或教程,然后进行一些基础学习。

以下是一些在线文章/教程可以帮助您解决此特定查询:

MSDN教程 - An Overview of Inserting, Updating, and Deleting Data

YouTube链接 - GridView insert update delete in asp.net

谷歌搜索可以引导您获得更多此类学习资源 https://www.google.com/search?q=tutorial+to+load+gridview+update+delete+asp.net

答案 2 :(得分:0)

一查一下这些链接可能会有所帮助

  1. example
  2. example with explination