【问题标题】:delete record from gridview but not from database从gridview中删除记录,但不从数据库中删除
【发布时间】:2014-05-05 05:59:37
【问题描述】:

我正在尝试从网格中删除记录,而不是从数据库中。

当从gridview中删除数据但不想从db中删除记录时,我想设置数据库字段ISDeleted 1。

我的代码从 gridview 和 db 中删除记录。

在哪里更改我的代码-

 string strcon = ConfigurationManager.ConnectionStrings["Dbconnection"].ConnectionString;
SqlCommand command;
protected void Page_Load(object sender, EventArgs e)
{
    tblAdd.Visible = false;
    Label1.Visible = false;
    //GridView1.DataBind();
    if (!Page.IsPostBack)
        {
            fillLanguageGrid();
        }
}

public void fillLanguageGrid()
    {   
        GridView1.DataSourceID = "SqlDataSource1";
        GridView1.DataBind(); 
    }

protected void btnDelete_Click(object sender, EventArgs e)
{
    foreach (GridViewRow gvrow in GridView1.Rows)
    {
        CheckBox chkdelete = (CheckBox)gvrow.FindControl("chk");
        if (chkdelete.Checked)
        {
            string name= Convert.ToString(GridView1.DataKeys[gvrow.RowIndex].Values["Name"].ToString());
           // command.Parameters.Add(new SqlParameter("@status", SqlDbType.VarChar, 50));
            deleteRecordByName(name);
        }
    }
    fillLanguageGrid();
}

public void deleteRecordByName(string Name)
{
    SqlConnection sqlConnection = new SqlConnection(strcon);
    using (SqlCommand command = new SqlCommand("[dbo].[hrm_Langauges]", sqlConnection))
    {
        //  define this to be a stored procedure
        command.CommandType = CommandType.StoredProcedure;
        command.Parameters.Add(new SqlParameter("@status", SqlDbType.VarChar, 50));
        // define the parameter and set its value
        command.Parameters.Add(new SqlParameter("@Name", SqlDbType.VarChar)).Value = Name;
        command.Parameters.Add(new SqlParameter("@IsDeleted", SqlDbType.Bit)).Value = 1;
        command.Parameters["@status"].Value = "Delete";
        //open connection, execute DELETE query, close connection
        sqlConnection.Open();
        command.ExecuteNonQuery();
        sqlConnection.Dispose();
    }

}

【问题讨论】:

    标签: asp.net sql-server gridview stored-procedures


    【解决方案1】:

    为此,您需要在各自的数据库表中添加一列是否显示该记录。例如:添加列,如 Visible int

    假设如果

    Visible =1 --> 在 gridview 中显示该记录

    Visible =0 --> 在 gridview 中隐藏该记录

    默认情况下使 Visible =1 所以所有记录都显示在 gridview 中(像 Select ......Where Visible =1 这样编写查询)。当你尝试删除记录使用 update query 需要更新 Visible1 到 0。所以你的 gridview 只显示可见 =1 的记录。该特定已删除记录未显示在您的网格视图中,因为它的 Visible 列是 0。试试这个..

    【讨论】:

      猜你喜欢
      • 2019-06-11
      • 2018-12-07
      • 1970-01-01
      • 1970-01-01
      • 2013-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多