c# - 一键插入,更新,删除数据库

标签 c# sql-server winforms

我有一个应用程序,使用户从列表中选择一个项目,然后显示该项目的组件,并在单击组件时,用该组件的库存(大小和数量)填充dataGridView。

我想这样做,以便用户仅使用一个“保存”按钮就可以修改dataGridView中的数字以及数据库中的UPDATE,INSERT和DELETE。

我设法使这些功能分开工作,但是我不知道如何将它们全部集中在一个button_click事件中。

例如,这是我的更新功能:

 private void buttonSave_Click(object sender, EventArgs e)
 {
     using (SqlConnection con = new SqlConnection(conString))
         {
             con.Open();
             if (con.State == ConnectionState.Open)
             {
                foreach (DataGridViewRow row in dataGridViewStock.Rows)
                {
                    if (row.Cells[0].Value != null && row.Cells[1].Value != null)
                    {
                        SqlCommand update = new SqlCommand("UPDATE stock_test SET quantity=" + row.Cells[1].Value + " WHERE size=" + row.Cells[0].Value+ "AND codeArticleComponent ='" +labelComponentChosen.Text+ "'" , con);
                        update.ExecuteNonQuery();
                        update.Parameters.Clear();
                    }
                }    
            }
        }


编辑:我知道此应用程序的较旧版本通过简单地删除整个表并再次插入所有值来管理此问题,但我不想这样做,因为它似乎完全不安全,并且表将以较大的大小结尾。

最佳答案

有时需要使用单个存储过程在GridView中插入,更新和删除记录,而不是为每个操作创建单独的存储过程。

假设我有一个.aspx网页,我需要在其中插入,查看,更新和删除记录。为此,不是创建四个存储过程来执行这些任务,而是创建单个存储过程来满足我的要求,并且根据最终用户在单击按钮时执行的操作,我将在后面的代码中对其进行访问。

我写这篇文章的重点是新手,以及任何想使用单一存储过程在GridView中插入,更新和删除记录的人,因此让我们从基本介绍开始。

首先,将名为employee的表创建为:
我在id列上设置了主键,并且将Identity规范设置为Yes。

现在,我们有一个表来执行这些操作。现在让我们开始创建存储过程。

使用关键字Create Procedure和过程名称创建存储过程。让我们创建名为“ EmpEntry”的存储过程,如下所示:

create Procedure EmpEntry
(
  --variable  declareations 
 @Action Varchar (10),    --to perform operation according to string ed to this varible such as Insert,update,delete,select      
 @id int=null,    --id to perform specific task
 @FnameVarchar (50)=null,   -- for FirstName
 @MName Varchar (50)=null,   -- for MName
 @Lname Varchar (50)=null    -- for LastName
)
as
Begin 
  SET NOCOUNT ON;

If @Action='Insert'   --used to insert records
Begin
   Insert Into employee (FirstName,MName,LastName)values(@Fname,@MName,@Lname)
End  
else if @Action='Select'   --used to Select records
Begin
    select *from employee
end
else if @Action='Update'  --used to update records
Begin
   update employeeset FirstName=@Fname,MName=@MName,LastName=@Lname where id=@id
 End
 Else If @Action='delete'  --used to delete records
 Begin
   delete from employeewhere id=@id
 end
 End


上面的“存储过程”中的注释清楚地说明了哪个块用于哪个目的,因此我再次对其进行了简要说明。我使用了@Action变量并为它们分配了字符串,并且根据存储过程中的参数,将执行特定的块,因为如果有条件语句,则将这些块或条件嵌套在其中。

最重要的是,我为每个变量分配了null以避免对存储过程的参数产生影响,因为我们要给存储过程使用不同数量的参数,但是要使用不同数量的参数来执行这些操作任务。

现在,将一个示例应用程序“ Empsys”创建为:

"Start" - "All Programs" - "Microsoft Visual Studio 2010".
"File" - "New Project" - "C#" - "Empty Web Application" (to avoid adding a master page).


根据需要为网站提供一个名称,例如“ Empsys”或其他名称,然后指定位置。
然后右键单击解决方案资源管理器-“添加新项”-“ Default.aspx页面”。

将一个按钮,三个文本框,一个GridView和一个隐藏字段拖放到数据库的隐藏值中,并将一个标签拖放到Default.aspx页的该部分上。

然后切换到设计视图; Default aspx页面源的部分将如下所示:

<form id="form1"runat="server">
    <div>
First Name  <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
Middle Name<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
Last Name <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
        <asp:ButtonID="Button1"runat="server"Text="save"onclick="Button1_Click" />
    </div>
<asp:HiddenField ID="HiddenField1" runat="server"/>
 <asp:GridViewID="GridView1"runat="server" >
     </asp:GridView>
</form>


现在,使用以下GridView事件属性执行事件,例如更新,删除,编辑取消等。让我们看看这些属性是什么:


DataKeyNames:这个属性我已经习惯了GridView的行索引
OnRowEditing:当用户单击编辑按钮时,此属性用于处理事件
OnRowCancelingEdit:当用户单击单击编辑按钮后存在的“取消”按钮时,此属性用于处理事件
OnRowDeleting:当用户单击删除按钮以删除GridView的行时,此属性用于处理事件
OnRowUpdating:当用户单击更新网格记录的更新按钮时,此属性用于处理事件


现在,我的网格将如下所示:

<asp:GridViewID="GridView1" runat="server" DataKeyNames ="id"OnRowEditing ="Edit"               
        OnRowCancelingEdit ="canceledit"    OnRowDeleting ="delete"    OnRowUpdating = "Update" >
 </asp:GridView>


在前面的GridView属性上,我分配了要为特定操作调用的方法名称。

在数据库中插入数据的方法

在设计页面上单击鼠标右键,查看代码,然后在default.aspx.cs页面中编写以下代码,以将插入的记录保存在数据库中:

protected void empsave(object sender, EventArgs e)
{
      connection();
      query =  "studentEntryView";          //Stored Procedure name 
      SqlCommand com = new SqlCommand(query, con);  //creating  SqlCommand  object
      com.CommandType = CommandType.StoredProcedure;  //here we declaring command type as stored Procedure

       /* adding paramerters to  SqlCommand below *\
      com.Parameters.AddWithValue("@Action", HiddenField1.Value).ToString();//for ing hidden value to preform insert operation
       com.Parameters.AddWithValue("@FName",TextBox1.Text.ToString());        //first Name
       com.Parameters.AddWithValue("@Mname ", TextBox2.Text.ToString());     //middle Name
       com.Parameters.AddWithValue("@LName ",TextBox3.Text.ToString());       //Last Name
       com.ExecuteNonQuery();                     //executing the sqlcommand
       Label1.Visible = true;
       Label1.Text = "Records are Submitted Successfully";
}


现在创建方法,以查看GridView中的记录:

public void viewdata()

{
    connection();
    query = "studentEntryView";
    SqlCommand com = new SqlCommand(query, con);
    com.CommandType = CommandType.StoredProcedure;
    com.Parameters.AddWithValue("@Action", HiddenField2.Value).ToString();
    DataSet ds =new DataSet();
    SqlDataAdapter da =  new SqlDataAdapter(com);
    da.Fill(ds);
    GridView1.DataSource = ds;
    GridView1.DataBind();
}


以下是“ OnRowEditing”事件的方法:

protected void edit(objectsender, GridViewEditEventArgs e)

{

    GridView1.EditIndex= e.NewEditIndex;

    gedata();

}


以下是“ OnRowCancelingEdit”事件的方法:

protected void  canceledit(object sender, GridViewCancelEditEventArgs e)

{

    GridView1.EditIndex = -1;

    gedata();

}


以下是“ OnRowDeleting”事件的方法:

protected void delete(object sender, GridViewDeleteEventArgs e)
{
      connection();

      int id =  int.Parse(GridView1.DataKeys[e.RowIndex].Value.ToString());

      HiddenField1.Value = "Delete";

      query = "EmpEntry";

      com = new SqlCommand(query, con);

      com.CommandType =CommandType .StoredProcedure;

      com.Parameters.AddWithValue("@Action", HiddenField1.Value).ToString();

      com.Parameters.AddWithValue("id", SqlDbType.Int).Value = id;

      com.ExecuteNonQuery();

      con.Close();

      gedata();                 

 }


以下是“ OnRowUpdating”事件的方法:

protected void update(object sender, GridViewUpdateEventArgs e)
{
     connection();

     int id=int.Parse(GridView1.DataKeys[e.RowIndex].Value.ToString());

     HiddenField1.Value = "update";

     query = "EmpEntry";

     com = new SqlCommand(query, con);

     com.CommandType = CommandType.StoredProcedure;

     com.Parameters.AddWithValue("@Action", HiddenField1.Value).ToString();

     com.Parameters.AddWithValue("@FName", ((TextBox)GridView1.Rows[e.RowIndex].Cells[3].Controls[0]).Text.ToString());

     com.Parameters.AddWithValue("@MName", ((TextBox)GridView1.Rows[e.RowIndex].Cells[4].Controls[0]).Text.ToString());

     com.Parameters.AddWithValue("@LName", ((TextBox)GridView1.Rows[e.RowIndex].Cells[5].Controls[0]).Text.ToString());

     com.Parameters.AddWithValue("@id", SqlDbType.int ).Value = id;

     com.ExecuteNonQuery();

     con.Close();

     GridView1.EditIndex = -1;

     gedata();



}


代码简介

在上面的示例代码中,我使用了两个字符串查询来提供存储过程的名称,并使用constr来存储来自web.config文件的连接,另一件事是,我使用了一个隐藏字段来输入操作值我们的存储过程所必需的。

现在我们的应用程序可以使用了,按F5或其他,然后将一些值输入TextBox并按“保存”按钮。

现在,单击“保存”按钮后,隐藏字段值将使用“插入”值并将其作为操作输入到存储过程中,因此,存储过程将执行特定类型的块。

现在,在页面加载时,我已经调用了该方法,因此之后网格将按如下所示填充:

现在,单击调用编辑方法的“编辑”按钮,如以下网格所示:

如果单击“取消”按钮,则将调用editcancel方法,并取消编辑模式。现在,在网格TextBox中输入一些值,然后单击一个调用update方法的更新按钮,然后GridView中的记录将按照以下方式进行更新:

现在单击删除按钮,该按钮调用delete方法并从GridView中删除记录

注意
有关详细代码,请下载上面随附的zip文件。
    不要忘记为您的服务器位置更新Web.config文件。

关于c# - 一键插入,更新,删除数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48867987/

相关文章:

c# - 有条件的 LINQ ToArray()

c# - 来自 Javascript 的 ASMX Web 服务

sql - 如何在 SQL Server 中使用带有框架的窗口函数执行 COUNT(DISTINCT)

c# - 正则表达式检查文本是否包含两个单词之一和前面的数字

VB.NET 窗体高度问题

c# - 如何在 WinForm 应用程序的文本框中显示特定的数据库条目

c# - 使用 C# 创建 Azure DataDisk

c# - 通过非安全通道加载内容

sql - TSQL - 禁用事务中的触发器

c# - 在DataGridView中自动构建编号