如何从gridview中删除一行? [英] How do I delete a row from my gridview?

查看:98
本文介绍了如何从gridview中删除一行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,



我目前所做的是创建一个包含行的数据表并将其存储到会话中,然后在添加按钮上再次加载它在其中存储事件并存储用户输入,然后将其绑定到gridview。



当我单击添加按钮时,我立即将其插入数据库,并捕获在这种情况下,通过使用executioncalar()将FoodID存储在visible = false标签中,并将其用作数据表的一部分。



Gridview包含一个选择和删除链接按钮,其中选择突出显示该选项,删除使用FoodID作为标识符删除数据库中的记录。我的gridview在页面刷新时保留其数据。



我可以成功删除数据库中的记录,但在应用程序端删除行本身时会出现问题。以下是我的代码。我希望有人可以提供帮助,并提前致谢。



 受保护  void  Page_Load( object  sender,EventArgs e)
{
DataTable dtToGrid = < span class =code-keyword> new DataTable();

dtToGrid.Columns.Add( Date typeof string ));
dtToGrid.Columns.Add( MealType typeof string ));
dtToGrid.Columns.Add( Food& Drinks typeof string ));
dtToGrid.Columns.Add( WhereDidYouGetYourMeal? typeof string ));
dtToGrid.Columns.Add( Address typeof string ));
dtToGrid.Columns.Add( FoodID typeof string ));

会话[ dtToGrid] = dtToGrid;
}


受保护 void btnAdd2_Click(< span class =code-keyword> object sender,EventArgs e)
{
FoodExposure f1 = new FoodExposure();
f1.Day = Select1.Value.ToString();
f1.MealType = ddlMealtype1.Value.ToString();
f1.FoodAndDrink = tbxFood1.Value.ToString();
f1.MealPreparedFrom = ddlWhere1.Value.ToString();
f1.LocationOfMeal = inputTextAddress.Value.ToString();

int FoodID = DBManager.InsertFoodExposure(f1);
lblID.Text = FoodID.ToString();
lblID.Visible = false ;

DataTable dtToGrid =(DataTable)会话[ dtToGrid];

DataRow drToGrid = dtToGrid.NewRow();

drToGrid [ 日期] = Select1.Value.ToString() ;
drToGrid [ MealType] = ddlMealtype1.Value.ToString();
drToGrid [ Food& Drinks] = tbxFood1.Value.ToString();
drToGrid [ WhereDidYouGetYourMeal?] = ddlWhere1.Value.ToString();
drToGrid [ Address] = inputTextAddress.Value.ToString();
drToGrid [ FoodID] = lblID.Text.ToString();
dtToGrid.Rows.Add(drToGrid);

GridView1.Visible = true ;
GridView1.DataSource = dtToGrid;
GridView1.DataBind();

// 检查ViewState是否有相关数据。如果
if (ViewState [ CurrentData]!= null
{
DataTable dt =(DataTable)ViewState [ CurrentData];
int count = dt.Rows.Count;
BindGrid(伯爵);
}
其他
{
BindGrid( 1 );
}
Select1.Value = string .Empty;
ddlMealtype1.Value = string .Empty;
tbxFood1.Value = string .Empty;
ddlWhere1.Value = string .Empty;
inputTextAddress.Value = string .Empty;
lblID.Text = string .Empty;

Select1.Focus();
ddlMealtype1.Focus();
tbxFood1.Focus();
ddlWhere1.Focus();
inputTextAddress.Focus();
lblID.Focus();

}

private void BindGrid(< span class =code-keyword> int rowcount)
{
DataTable dt = new DataTable();
DataRow博士;
dt.Columns.Add( new System.Data.DataColumn( Date typeof String )));
dt.Columns.Add( new System.Data.DataColumn( MealType typeof String )));
dt.Columns.Add( new System.Data.DataColumn( Food& Drinks typeof String )));
dt.Columns.Add( new System.Data.DataColumn( WhereDidYouGetYourMeal? typeof String )));
dt.Columns.Add( new System.Data.DataColumn( 地址 typeof String )));
dt.Columns.Add( new System.Data.DataColumn( FoodID typeof String )));


if (ViewState [ CurrentData]!= null
{
for int i = 0 ; i < ; rowcount + 1 ; i ++)
{
dt =(DataTable)ViewState [ CurrentData];
if (dt.Rows.Count > 0
{
dr = dt.NewRow();
dr [ 0 ] = dt.Rows [ 0 ] [ 0 ]的ToString();

}
}
dr = dt.NewRow();
dr [ 0 ] = Select1.Value.ToString();
dr [ 1 ] = ddlMealtype1.Value.ToString();
dr [ 2 ] = tbxFood1.Value.ToString();
dr [ 3 ] = ddlWhere1.Value.ToString();
dr [ 4 ] = inputTextAddress.Value.ToString();
dr [ 5 ] = lblID.Text.ToString();
dt.Rows.Add(dr);

}
else
{
dr = dt.NewRow();
dr [ 0 ] = Select1.Value.ToString();
dr [ 1 ] = ddlMealtype1.Value.ToString();
dr [ 2 ] = tbxFood1.Value.ToString();
dr [ 3 ] = ddlWhere1.Value.ToString();
dr [ 4 ] = inputTextAddress.Value.ToString();
dr [ 5 ] = lblID.Text.ToString();

dt.Rows.Add(dr);

}

// 如果ViewState有数据则使用值为DataSource
如果(ViewState [ CurrentData]!= null
{
GridView1.DataSource =(DataTable)ViewState [< span class =code-string>
CurrentData];
GridView1.DataBind();
}
其他
{
// < span class =code-comment>使用DataTable中关联的初始数据绑定GridView
GridView1.DataSource = dt;
GridView1.DataBind();

}
// 将DataTable存储在ViewState中以保留值
ViewState [ CurrentData] = dt;

}


受保护 void GridView1_RowDeleting( object sender,GridViewDeleteEventArgs e)
{

int rowsdeleted = 0 ;

SqlConnection conn = null ;
try
{
conn = new SqlConnection();
conn.ConnectionString = ConfigurationManager.ConnectionStrings [ NDBConnectionString]。ConnectionString;
conn.Open();
SqlCommand comm = new SqlCommand();
comm.Connection = conn;
comm.CommandText = 从FoodExposure中删除,其中FoodID = @ FoodID;
comm.Parameters.AddWithValue( @ FoodID,Convert.ToInt32(GridView1.SelectedRow) .Cells [ 7 ]。Text));
rowsdeleted = comm.ExecuteNonQuery();
conn.Close();
}
catch (SqlException es)
{
throw es;
}
}

解决方案

1.您的代码中有一些错误:

i)第一个问题是你有6列,但是你试图从第8列获得 foodID ,并且应该从第6个位置开始,如: GridView1.SelectedRow.Cells [5] .Text 或更好,您可以使用 GridViewDeleteEventArgs的 Keys 属性参数。



ii)其次,从数据库中删除当前项后,必须使用 GridView1.DataBind()刷新网格绑定



2.我有一篇关于在ASP.NET中使用GridView的文章,你可以在那里找到CRUD的源代码示例(Create,使用更好的方法读取,更新,删除)操作:

高级ASPX GridView分页和数据实体 [ ^ ]


参考:在ASP.NET Gridview中插入,更新,删除,将DataSource作为SQL Server,MS Access(mdb / accdb),XML和Framework作为2.0 / 3.0 / 3.5 / 4.0(VS 2005/2008/2010) [ ^

Hello everyone,

What I have currently done is to create a datatable containing rows and store it into session, load it again at a "Add" button click event and store user input in it, and then bind it to a gridview.

When I click the "Add" button, I insert it into database immediately, and capture the ID which is in this case FoodID by using executescalar(), store it in a "visible = false" label and use it as part of the datatable.

The Gridview contains a "Select" and "Delete" link buttons, where "Select" highlights the option and "Delete" deletes the record in the database using the FoodID as the identifier. My gridview retains its data upon page refresh.

I can successfully delete the record in the database, but have problems deleting the row itself on the application side. Below are my codes. I hope someone can help, and thanks in advance.

protected void Page_Load(object sender, EventArgs e)
        {
            DataTable dtToGrid = new DataTable();

            dtToGrid.Columns.Add("Date", typeof(string));
            dtToGrid.Columns.Add("MealType", typeof(string));
            dtToGrid.Columns.Add("Food&Drinks", typeof(string));
            dtToGrid.Columns.Add("WhereDidYouGetYourMeal?", typeof(string));
            dtToGrid.Columns.Add("Address", typeof(string));
            dtToGrid.Columns.Add("FoodID", typeof(string));

            Session["dtToGrid"] = dtToGrid;
        }


protected void btnAdd2_Click(object sender, EventArgs e)
        {
            FoodExposure f1 = new FoodExposure();
            f1.Day = Select1.Value.ToString();
            f1.MealType = ddlMealtype1.Value.ToString();
            f1.FoodAndDrink = tbxFood1.Value.ToString();
            f1.MealPreparedFrom = ddlWhere1.Value.ToString();
            f1.LocationOfMeal = inputTextAddress.Value.ToString();

            int FoodID = DBManager.InsertFoodExposure(f1);
            lblID.Text = FoodID.ToString();
            lblID.Visible = false;

            DataTable dtToGrid = (DataTable)Session["dtToGrid"];

            DataRow drToGrid = dtToGrid.NewRow();

            drToGrid["Date"] = Select1.Value.ToString();
            drToGrid["MealType"] = ddlMealtype1.Value.ToString();
            drToGrid["Food&Drinks"] = tbxFood1.Value.ToString();
            drToGrid["WhereDidYouGetYourMeal?"] = ddlWhere1.Value.ToString();
            drToGrid["Address"] = inputTextAddress.Value.ToString();
            drToGrid["FoodID"] =  lblID.Text.ToString();
            dtToGrid.Rows.Add(drToGrid);

            GridView1.Visible = true;
            GridView1.DataSource = dtToGrid;
            GridView1.DataBind();

            // Check if the ViewState has a data assoiciated within it. If
            if (ViewState["CurrentData"] != null)
            {
                DataTable dt = (DataTable)ViewState["CurrentData"];
                int count = dt.Rows.Count;
                BindGrid(count);
            }
            else
            {
                BindGrid(1);
            }
            Select1.Value = string.Empty;
            ddlMealtype1.Value = string.Empty;
            tbxFood1.Value = string.Empty;
            ddlWhere1.Value = string.Empty;
            inputTextAddress.Value = string.Empty;
            lblID.Text = string.Empty;

            Select1.Focus();
            ddlMealtype1.Focus();
            tbxFood1.Focus();
            ddlWhere1.Focus();
            inputTextAddress.Focus();
            lblID.Focus();

        }

        private void BindGrid(int rowcount)
        {
            DataTable dt = new DataTable();
            DataRow dr;
            dt.Columns.Add(new System.Data.DataColumn("Date", typeof(String)));
            dt.Columns.Add(new System.Data.DataColumn("MealType", typeof(String)));
            dt.Columns.Add(new System.Data.DataColumn("Food&Drinks", typeof(String)));
            dt.Columns.Add(new System.Data.DataColumn("WhereDidYouGetYourMeal?", typeof(String)));
            dt.Columns.Add(new System.Data.DataColumn("Address", typeof(String)));
            dt.Columns.Add(new System.Data.DataColumn("FoodID", typeof(String)));


            if (ViewState["CurrentData"] != null)
            {
                for (int i = 0; i < rowcount + 1; i++)
                {
                    dt = (DataTable)ViewState["CurrentData"];
                    if (dt.Rows.Count > 0)
                    {
                        dr = dt.NewRow();
                        dr[0] = dt.Rows[0][0].ToString();

                    }
                }
                dr = dt.NewRow();
                dr[0] = Select1.Value.ToString();
                dr[1] = ddlMealtype1.Value.ToString();
                dr[2] = tbxFood1.Value.ToString();
                dr[3] = ddlWhere1.Value.ToString();
                dr[4] = inputTextAddress.Value.ToString();
                dr[5] = lblID.Text.ToString();
                dt.Rows.Add(dr);

            }
            else
            {
                dr = dt.NewRow();
                dr[0] = Select1.Value.ToString();
                dr[1] = ddlMealtype1.Value.ToString();
                dr[2] = tbxFood1.Value.ToString();
                dr[3] = ddlWhere1.Value.ToString();
                dr[4] = inputTextAddress.Value.ToString();
                dr[5] = lblID.Text.ToString();

                dt.Rows.Add(dr);

            }

            // If ViewState has a data then use the value as the DataSource
            if (ViewState["CurrentData"] != null)
            {
                GridView1.DataSource = (DataTable)ViewState["CurrentData"];
                GridView1.DataBind();
            }
            else
            {
                // Bind GridView with the initial data assocaited in the DataTable
                GridView1.DataSource = dt;
                GridView1.DataBind();

            }
            // Store the DataTable in ViewState to retain the values
            ViewState["CurrentData"] = dt;

        }

   
        protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {

            int rowsdeleted = 0;

            SqlConnection conn = null;
            try
            {
                conn = new SqlConnection();
                conn.ConnectionString = ConfigurationManager.ConnectionStrings["NDBConnectionString"].ConnectionString;
                conn.Open();
                SqlCommand comm = new SqlCommand();
                comm.Connection = conn;
                comm.CommandText = "Delete from FoodExposure where FoodID=@FoodID";
                comm.Parameters.AddWithValue("@FoodID", Convert.ToInt32(GridView1.SelectedRow.Cells[7].Text));
                rowsdeleted = comm.ExecuteNonQuery();
                conn.Close();
            }
            catch (SqlException es)
            {
                throw es;
            }
        }

解决方案

1.You have some errors in your code:
i)first problem is that you have 6 columns but you are trying to get the foodID from the 8th one, and should be from 6th position like: GridView1.SelectedRow.Cells[5].Text or better you could use the Keys property of your GridViewDeleteEventArgs parameter.

ii)Secondly, after you delete the current item from the database, you have to refresh the grid binding by using GridView1.DataBind()

2.I have an article about using GridView in ASP.NET and there your could find source code example also for CRUD (Create, Read, Update, Delete) operations by using a better approach:
Advanced ASPX GridView Pagination and Data Entities[^]


Refer: Insert, Update, Delete in ASP.NET Gridview, DataSource as SQL Server, MS Access (mdb/accdb), XML and Framework as 2.0 / 3.0 / 3.5 / 4.0 (VS 2005/2008/2010)[^]


这篇关于如何从gridview中删除一行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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