ASP.NET - working with GridView Programmatically
- by JMSA
I am continuing from this post.
After much Googling, I have come up with this code to edit cells programmatically:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Ice_Web_Portal.BO;
namespace GridView___Test
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
GridView1.DataSource = Course.GetCourses();
GridView1.DataBind();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridViewRow row = GridView1.Rows[e.NewEditIndex];
GridView1.EditIndex = e.NewEditIndex;
GridView1.DataSource = Course.GetCourses();
GridView1.DataBind();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
TextBox txtID = (TextBox)GridView1.Rows[e.RowIndex].Cells[1].Controls[0];
TextBox txtCourseCode = (TextBox)GridView1.Rows[e.RowIndex].Cells[2].Controls[0];
TextBox txtCourseName = (TextBox)GridView1.Rows[e.RowIndex].Cells[3].Controls[0];
TextBox txtCourseTextBookCode = (TextBox)GridView1.Rows[e.RowIndex].Cells[4].Controls[0];
Course item = new Course();
item.ID = Convert.ToInt32(txtID.Text);
item.CourseCode = txtCourseCode.Text;
item.CourseName = txtCourseName.Text;
item.TextBookCode = txtCourseTextBookCode.Text;
bool success = Course.Update(item);
labMessage.Text = success.ToString();
GridView1.EditIndex = -1;
GridView1.DataSource = Course.GetCourses();
GridView1.DataBind();
}
}
}
But 2 problems are happening.
(1) I need to press command buttons twice to Edit/Update.
(2) Changes in the cell values are not updated in the database. I.e. edited cell values are not committing.
Can anyone give me a solution?