从网格视图中删除行后如何将数据重新绑定或填充到gridview [英] After deleting a row from grid view How to rebind or fill data to gridview

查看:67
本文介绍了从网格视图中删除行后如何将数据重新绑定或填充到gridview的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用sqlserver,三层架构和存储过程...



我的aspx页面




I am using sqlserver, three tier architecture and store procedure for this...

My aspx Page


<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
               onrowcancelingedit="GridView1_RowCancelingEdit"
               onrowdeleting="GridView1_RowDeleting" onrowediting="GridView1_RowEditing"
               onrowupdating="GridView1_RowUpdating">
           <Columns>
           <asp:TemplateField HeaderText="ProductId">
           <ItemTemplate>
           <asp:Label ID="lblProductId" runat="server" Text='<%#Eval("ProductId") %>'>'> </asp:Label>
           </ItemTemplate>
           </asp:TemplateField>
            <asp:TemplateField HeaderText="ProductCategory">
           <ItemTemplate>
           <asp:Label ID="lblProcuctCategory" runat="server" Text='<%#Eval("ProductCategory") %>'>'> </asp:Label>
           </ItemTemplate>
           <EditItemTemplate>
           <asp:TextBox ID="txtProductCategory" runat="server" Text='<%#Eval("ProductCategory") %>'>' ></asp:TextBox>
           </EditItemTemplate>
           </asp:TemplateField>
            <asp:TemplateField HeaderText="GirthFrom">
           <ItemTemplate>
           <asp:Label ID="lblGirthFrom" runat="server" Text='<%#Eval("GirthFrom") %>'>'> </asp:Label>
           </ItemTemplate>
           <EditItemTemplate>
           <asp:TextBox ID="txtGirthfrom" runat="server" Text='<%#Eval("GirthFrom") %>'>' ></asp:TextBox>
           </EditItemTemplate>
           </asp:TemplateField>
            <asp:TemplateField HeaderText="GirthTo">
           <ItemTemplate>
           <asp:Label ID="lblGirthTo" runat="server" Text='<%#Eval("GirthTo") %>'>'> </asp:Label>
           </ItemTemplate>
           <EditItemTemplate>
           <asp:TextBox ID="txtGirthTo" runat="server" Text='<%#Eval("GirthTo") %>'>' ></asp:TextBox>
           </EditItemTemplate>
           </asp:TemplateField>
               <asp:TemplateField HeaderText="Action">
                   <ItemTemplate>
                       <asp:LinkButton ID="edit" runat="server" CommandName="Edit" Text="Edit"></asp:LinkButton>
                       <asp:LinkButton ID="Delete" runat="server" CommandName="Delete" Text="Delete"></asp:LinkButton>
                   </ItemTemplate>
                   <EditItemTemplate>
                       <asp:LinkButton ID="Update" runat="server" CommandName="Update" Text="Update"></asp:LinkButton>
                       <asp:LinkButton ID="Cancel" runat="server" CommandName="Cancel" Text="cancel"></asp:LinkButton>
                   </EditItemTemplate>
               </asp:TemplateField>
           </Columns>
           </asp:GridView>









我的aspx.cs页面









My aspx.cs Page


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

public partial class _Default : System.Web.UI.Page
{
    Creation obj=new Creation();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {

            Gridviewdatabind();
        }
            
        
    }
    private void Gridviewdatabind()
    {
        DataTable dt = obj.display1();
            GridView1.DataSource = dt;
            GridView1.DataBind();
    }

    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        string lblProductId = ((Label)GridView1.Rows[e.RowIndex].FindControl("lblProductId")).Text;
        obj.ProductId = Convert.ToInt32(lblProductId);
        int res = obj.delete();
        Gridviewdatabind();
        
        
    }
    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        Gridviewdatabind();
    }
    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        string lblProductId = ((Label)GridView1.Rows[e.RowIndex].FindControl("lblProductId")).Text;

        string txtProductCategory = ((TextBox)GridView1.Rows[e.RowIndex]
                           .FindControl("txtProductCategory")).Text;
        string txtGirthFrom = ((TextBox)GridView1.Rows[e.RowIndex]
                           .FindControl("txtGirthFrom")).Text;
        string txtGirthTo = ((TextBox)GridView1.Rows[e.RowIndex]
                               .FindControl("txtGirthTo")).Text;
        obj.ProductCategory = txtProductCategory;
        obj.GirthFrom = Convert.ToInt32(txtGirthFrom);
        obj.GirthTo = Convert.ToInt32(txtGirthTo);
        obj.ProductId = Convert.ToInt32(lblProductId);
        int res = obj.update();
        GridView1.EditIndex = -1;
        Gridviewdatabind();

    }
    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        GridView1.EditIndex = -1;
        Gridviewdatabind();
    }
    
}







我的数据层(databaseoperatio类文件)






My Datalayer(databaseoperatio class file)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web; 
using System.Data;
using System.Data.SqlClient;

/// <summary>
/// Summary description for DBoperations
/// </summary>
public class DBoperations
{

    SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=Micro;Integrated Security=True");
    SqlCommand cmd = new SqlCommand();
	public DBoperations()
	{
        cmd.Connection = con;
		//
		// TODO: Add constructor logic here
		//
	}

public DataTable display1(Creation obj)
    {
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.CommandText = "SP_SelectCatgory"; 
        con.Open();
        DataTable dt = new DataTable();
        SqlDataAdapter sda = new SqlDataAdapter(cmd);
        sda.Fill(dt);
        con.Close();
        return dt;
    }

public int DELETECREATION(Creation obj)
    {
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.CommandText = "SP_DeleteCategory";
        cmd.Parameters.AddWithValue("@pdtid", obj.ProductId);
        con.Open();
        int res = cmd.ExecuteNonQuery();
        con.Close();
        return res;
    }





我的属性层(类文件)









My property layer(class file)



using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;

/// <summary>
/// Summary description for Creation
/// </summary>
public class Creation
{
    DBoperations dbo = new DBoperations();
    private string _pdtctg;
    private int _girfrom;
    private int _girto;
    private int _id;


    public string ProductCategory
    {
        get
        {
            return _pdtctg;
        }
        set
        {
            _pdtctg = value;
        }
    }
    public int GirthFrom
    {
        get
        {
            return _girfrom;
        }
        set
        {
            _girfrom = value;
        }
    }
    public int GirthTo
    {
        get
        {
            return _girto;
        }
        set
        {
            _girto = value;
        }
    }
    public int ProductId
    {
        get
        {
            return _id;
        }
        set
        {
            _id = value;
        }
    }




    public Creation()
    {
        //
        // TODO: Add constructor logic here
        //
    }

    public DataTable display1()
    {
        DataTable dt = dbo.display1(this);
        return dt;

    }



    public int delete()
    {
        int res = dbo.DELETECREATION(this);
        return res;
    }





我存储的程序

//选择查询的存储过程





My stored Procedures
//stored procedure for select query

ALTER PROCEDURE SP_SelectCatgory



AS
BEGIN
select * from Categorycrt order by ProductId desc

    END



//删除查询的存储过程< br $>



//stored procedure for delete query

ALTER PROCEDURE SP_DeleteCategory(@pdtid int)

AS
    BEGIN
    delete from categorycrt where ProductId=@pdtid
    END









该代码适用于gridvew的初始填充以及删除后或更新行gridview不重新绑定;它没有填充新数据表被删除或更新,数据被更新并从数据表中删除但它没有填写网格视图抛出异常



显示的错误是:用户代码未处理Sqlexception ::





The code is working for the intial fill of gridvew and after delete or update of rows the gridview is not rebind ;its not filling back with the new datatable deleted or update, the data is updated and deleted from datatable but it is not filling in grid view an exceptio is thrown

Error shown is : Sqlexception was unhandled by user code::

Procedure SP_SelectCatgory has no parameters and arguments were supplied.





请帮助我



Kindly help me please

推荐答案

在调用SP之前清除命令参数。



试试这个





公共DataTable displ ay1(Creation obj)

{

cmd.Parameters.Clear();

cmd.CommandType = CommandType .StoredProcedure;

cmd.CommandText =SP_SelectCatgory;

con.Open();

DataTable dt = new DataTable();

SqlDataAdapter sda = new SqlDataAdapter(cmd);

sda.Fill(dt);

con.Close();

return dt;

}
Clear command parameters before calling SP.

Try this


public DataTable display1(Creation obj)
{
cmd.Parameters.Clear();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "SP_SelectCatgory";
con.Open();
DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
con.Close();
return dt;
}


你正在使用相同的SQLCommand类来删除和显示记录

在删除记录时你添加了一个参数这些参数被转发到显示方法但是在你的选择SP中有这样的参数可用这就是为什么你会收到错误



尝试在我的数据层(数据库操作类文件)中这样做



You are using same SQLCommand class for both deleting and displaying records
while deleting record you have added one parameter these parameter is carry forwarded to display method but in your select SP there is Such Parameter available That is Why you are getting error

Try to do like this in My Datalayer(databaseoperatio class file)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web; 
using System.Data;
using System.Data.SqlClient;
 
/// <summary>
/// Summary description for DBoperations
/// </summary>
public class DBoperations
{
 
    SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=Micro;Integrated Security=True");
    SqlCommand cmd = null;
	public DBoperations()
	{
		//
		// TODO: Add constructor logic here
		//
	}
 
public DataTable display1(Creation obj)
    {
        cmd= new SqlCommand();
        cmd.Connection = con;

        cmd.CommandType = CommandType.StoredProcedure;
        cmd.CommandText = "SP_SelectCatgory"; 
        con.Open();
        DataTable dt = new DataTable();
        SqlDataAdapter sda = new SqlDataAdapter(cmd);
        sda.Fill(dt);
        con.Close();
        return dt;
    }
 
public int DELETECREATION(Creation obj)
    {
        cmd= new SqlCommand();
        cmd.Connection = con;

        cmd.CommandType = CommandType.StoredProcedure;
        cmd.CommandText = "SP_DeleteCategory";
        cmd.Parameters.AddWithValue("@pdtid", obj.ProductId);
        con.Open();
        int res = cmd.ExecuteNonQuery();
        con.Close();
        return res;
    }


不共享连接和命令对象。作为最佳实践,在需要时创建连接,命令,将其与您完成的操作一起部署。检查以下代码。



Don't share the connection and command objects. As a best practice, create connection, commands when needed, dispose it ones you done with it. check below code.

public class DBoperations
{
    public const string CONNECTION_STRING = "Data Source=.;Initial Catalog=Micro;Integrated Security=True";

    public DBoperations()
    {
    }

    public static DataTable display1(Creation obj)
    {
        using (SqlConnection con = new SqlConnection(CONNECTION_STRING))
        using (SqlCommand cmd = new SqlCommand("SP_SelectCatgory", con))
        {
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = "SP_SelectCatgory";
            con.Open();
            DataTable dt = new DataTable();
            using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
            {
                sda.Fill(dt);
                con.Close();
                return dt;
            }
        }
    }

    public static int DELETECREATION(Creation obj)
    {
        using (SqlConnection con = new SqlConnection(CONNECTION_STRING))
        using (SqlCommand cmd = new SqlCommand("SP_DeleteCategory", con))
        {
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@pdtid", obj.ProductId);
            con.Open();
            int res = cmd.ExecuteNonQuery();
            return res;
        }

    }
}





then you can call above methods as



then you can call above methods as

DBoperations.display1(obj);
DBoperations.DELETECREATION(obj);





note that you have not following any naming conventions. try to follow coding standards.



note that you have not following any naming conventions. try to follow coding standards.


这篇关于从网格视图中删除行后如何将数据重新绑定或填充到gridview的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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