Click here to Skip to main content
15,884,537 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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.

C#
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;
            }
        }
Posted
Updated 21-Aug-14 21:58pm
v3
Comments
Herman<T>.Instance 21-Aug-14 11:21am    
why have a datatable in session? Why.....
After the executenonquery you do not rebind your gridview. That is why you do not see the updata
Member 10915623 21-Aug-14 11:42am    
I followed some online tutorials, they suggested it, sorry about that...
I tried rebinding it, but the deleted row appears again when I add something else.
It successfully gets deleted from the database though
Herman<T>.Instance 22-Aug-14 3:40am    
do you rebind the table from session or from database!
Member 10915623 22-Aug-14 3:56am    
I did not rebind the gridview at all, but the data is loaded from the web application itself, not the database. So I just need to delete that row from being displayed
Herman<T>.Instance 22-Aug-14 4:15am    
that delete the row from the table in session. If you don't do that the row keeps returning in your screen.

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[^]
 
Share this answer
 
Comments
Member 10915623 22-Aug-14 4:00am    
I have a "select" and "delete" links at the front, I do not know what error you encounter, but it works fine for me. When I use Cells[7], it correctly takes the foodID and deletes acordingly from the database
Raul Iloc 22-Aug-14 4:04am    
I do not have your code, but from quick review of the code provided by you, it seems that there is an error. So I thought that maybe the record was not deleted from the database. But if you are saying that is no problem at deleting, you could ignore this part from by solution!
Member 10915623 22-Aug-14 4:08am    
Thanks for the help though Raul, the only problem I face is the deletion of the row from the gridview and not the database. I just need that row to disappear, but simply cant find proper sources to get it to work
Member 10915623 22-Aug-14 4:01am    
I think GridView1.DataBind() works fine if I use SqlDataSource, but it does not work for the static page
Raul Iloc 22-Aug-14 4:10am    
You have to add "GridView1.DataBind()" in your "GridView1_RowDeleting" method after you deleting form DB part.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900