Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

Datagrid Operations

4.20/5 (3 votes)
25 Oct 2008CPOL 1   236  
This is to illustrate grid update operation

Introduction

This is an article/code snippet for datagrid update operation and delete operation with custom error message and enabling/disabling grid operations depending on various conditions.

Code

Let's begin in a step by step manner:

Step 1: Add Datagrid to webform.

Step 2: Disable auto generate column false.

Step 3: Now go to column property and create columns that you need.

Step 4: Add Edit Button and Delete button, and convert them as template columns (if you need to enable and disable them depending on conditions).

Bound_Column.JPG

Generating Events for Grid

We need Edit and Delete Grid Event and first we need to add the event handlers:

C#
private void InitializeComponent()
        {
            this.DataGrid1.PageIndexChanged += 
		new System.Web.UI.WebControls.DataGridPageChangedEventHandler
		(this.DataGrid1_PageIndexChanged);
            this.DataGrid1.CancelCommand += 
		new System.Web.UI.WebControls.DataGridCommandEventHandler
		(this.DataGrid1_CancelCommand);
            this.DataGrid1.EditCommand += 
		new System.Web.UI.WebControls.DataGridCommandEventHandler
		(this.DataGrid1_EditCommand);
            this.DataGrid1.UpdateCommand += 
		new System.Web.UI.WebControls.DataGridCommandEventHandler
		(this.DataGrid1_UpdateCommand);
}

Now we will add the events as follows:

C#
public void DataGrid1_EditCommand
	(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
        {
            DataGrid1.EditItemIndex = e.Item.ItemIndex;
            BindData();
        }
C#
public void DataGrid1_CancelCommand
	(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
        {
            // All we do in the cancel method is to assign '-1' 
            // to the datagrid editItemIndex
            // Once the edititemindex is set to '-1' the datagrid 
            // returns back to its original condition
            DataGrid1.EditItemIndex = -1;
            BindData();
        }

Update.JPG

C#
public void DataGrid1_UpdateCommand
	(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
        {
            //you need this code if you need to retrieve existing cell for verification
            System.Web.UI.WebControls.TableCell Id = 
			new System.Web.UI.WebControls.TableCell();
            System.Web.UI.WebControls.TableCell Name = 
			new System.Web.UI.WebControls.TableCell();
            System.Web.UI.WebControls.TableCell City = 
			new System.Web.UI.WebControls.TableCell();

            System.Web.UI.WebControls.TextBox NameVer = 
			new System.Web.UI.WebControls.TextBox();
            System.Web.UI.WebControls.TextBox CityVer = 
			new System.Web.UI.WebControls.TextBox();

            Id = (System.Web.UI.WebControls.TableCell)e.Item.Cells[0];
            Name = (System.Web.UI.WebControls.TableCell)e.Item.Cells[1];
            NameVer = (System.Web.UI.WebControls.TextBox)e.Item.Cells[2].Controls[1];
            City = (System.Web.UI.WebControls.TableCell)e.Item.Cells[3];
            CityVer = (System.Web.UI.WebControls.TextBox)e.Item.Cells[4].Controls[1];

            if (Name.Text.Trim() == NameVer.Text.Trim() && 
			City.Text.Trim() == CityVer.Text.Trim())
            {
                string Qry = "UPDATE User_Info SET Name =' " + Name.Text + 
		"',City ='" + City.Text + "',Status = 1 WHERE Id= " + Id.Text;
                SqlCommand myCommand = new SqlCommand(Qry, conn);
                myCommand.CommandType = CommandType.Text;
                conn.Open();
                myCommand.ExecuteNonQuery();
                conn.Close();
                DataGrid1.EditItemIndex = -1;
                BindData();
                ShowMessage("Value  Updated Successfully");
            }
            ShowMessage("Value Not Valid");
        } 
C#
public void DataGrid1_PageIndexChanged
	(object source, System.Web.UI.WebControls.DataGridPageChangedEventArgs e)
        {
            DataGrid1.CurrentPageIndex = e.NewPageIndex;
            BindData();
        }
C#
protected void DataGrid1_DeleteCommand(object source, DataGridCommandEventArgs e)
        {
            System.Web.UI.WebControls.TableCell Id = 
		new System.Web.UI.WebControls.TableCell();
            Id = (System.Web.UI.WebControls.TableCell)e.Item.Cells[0];
            string Qry = "Delete from  User_Info WHERE Id=" + Id.Text + "and status =1 ";
            SqlCommand myCommand = new SqlCommand(Qry, conn);
            myCommand.CommandType = CommandType.Text;
            conn.Open();
            int ans = myCommand.ExecuteNonQuery();
            conn.Close();
            DataGrid1.EditItemIndex = -1;
            BindData();
            if (ans ==1 )   ShowMessage("Value  Deleted Successfully");
            else ShowMessage("Not allowed to   Deleted non verified Records");
        } 

Now in page load, we need to load the data on the grid as follows:

C#
protected void Page_Load(object sender, System.EventArgs e)
        {
            // Put user code to initialize the page here
            if (!Page.IsPostBack)
            {
                BindData();
            }
        }
C#
public void BindData()
        {
            SqlCommand myCommand = new SqlCommand
	("select Id , Name , City , Phone , Status from User_Info", conn);
            myCommand.CommandType = CommandType.Text;
            SqlDataAdapter myAdapter = new SqlDataAdapter(myCommand);
            DataSet ds = new DataSet();
            myAdapter.Fill(ds, "tblPerson");
            conn.Open();
            myCommand.ExecuteNonQuery();
            DataGrid1.DataSource = ds;
            DataGrid1.DataBind();
            conn.Close();
        }

JavaScript is used to show custom message as below:

private void ShowMessage(string msgtext)
        {
            String msgString = "<script language="JavaScript">";
            msgString += "window.alert('" + msgtext + "');";
            msgString += "</script>";
            Page.RegisterStartupScript("showmessage", msgString);
        }

Following code is used to enable/disable the edit/delete links:

C#
public bool checkStatus(object data)
        {
            int val = Int32.Parse(data.ToString());
            if (val == 1)
                return false;
            else
                return true;
        }
C#
public string SetText(object data, object refcol, string title)
        {
            switch (title)
            {
                case "Status": if (Convert.ToInt16(refcol.ToString()) == 1)
                        return "Already Verified";
                    else
                        return "Verify";
                case "Delete": if (Convert.ToInt16(refcol.ToString()) == 1)
                        return "Delete";
                    else
                        return "Verify First";
                //case "PER"  : if (Convert.ToInt16(refcol.ToString()) == 1) 
                //              {
                //                  DateTime dt = Convert.ToDateTime(data.ToString());
                //                  return dt.ToShortDateString() ;
                //              }
                //              else	
                //                  return "";
                default: if (Convert.ToInt16(refcol.ToString()) == 1)
                        return data.ToString();
                    else
                        return "";
            }
            return "";
        }

You need some code in the HTML page as well. Please refer to the code for that.

History

  • 25th October, 2008: Initial post

License

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