Click here to Skip to main content
Licence CPOL
First Posted 25 Oct 2008
Views 10,483
Downloads 54
Bookmarked 18 times

Datagrid Operations

By Patel Vinay | 25 Oct 2008
This is to illustrate grid update operation

1

2

3
2 votes, 66.7%
4
1 vote, 33.3%
5
4.20/5 - 3 votes
μ 4.20, σa 1.01 [?]

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:

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:

public void DataGrid1_EditCommand
	(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
        {
            DataGrid1.EditItemIndex = e.Item.ItemIndex;
            BindData();
        }
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

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");
        } 
public void DataGrid1_PageIndexChanged
	(object source, System.Web.UI.WebControls.DataGridPageChangedEventArgs e)
        {
            DataGrid1.CurrentPageIndex = e.NewPageIndex;
            BindData();
        }
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:

protected void Page_Load(object sender, System.EventArgs e)
        {
            // Put user code to initialize the page here
            if (!Page.IsPostBack)
            {
                BindData();
            }
        }
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:

public bool checkStatus(object data)
        {
            int val = Int32.Parse(data.ToString());
            if (val == 1)
                return false;
            else
                return true;
        }
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)

About the Author

Patel Vinay

Web Developer

India India

Member


Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralGood article PinmemberDonsw7:07 30 Jan '09  
Good read, well thought out.
GeneralGood PinmemberMember 312464821:41 27 Oct '08  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web03 | 2.5.120210.1 | Last Updated 25 Oct 2008
Article Copyright 2008 by Patel Vinay
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid