Thursday, February 21, 2013

Example on Gridview with CRUD operations in Asp.net


Example on Gridview with CRUD operations in Asp.net

STEP1:
Create a web project. add a web form.
 go to an .aspx page,
 for example, Default.aspx, and add an ASP.NET GridView control from toolbox.
goto gridview code
write this sample code on it.

<asp:GridView ID="gridinfo" runat="server"
 AutoGenrationColumns="False" DataKeyNmes="Id,Type"
 OnRowCancelingEdit="grid_row_cancelingedit"
 OnRowDataBound="grid_row_databound"
 OnRowEditing="grid_row_editing"
 OnRowUpdating="grid_row_update"
 OnRowCommand="grid_row_command"
 OnRowDeleting="grid_row_delete"
 ShowFooter="True">

Columns Designing:
Here we design how our Grid will display.we can place controls in the GridView also.
now see the example.

<asp:TemplateField> is used to make columns.
<ItemTemplate> is used for bind data to the control.
<EditItemTemplate> is used to put edit control in GridView
<FooterTemplate> is used to display footer control.


.........................................................................................................................


1. Editing the data in Form controls is easy instead of editing Grid controls

2. No need to apply validations again because we are already applying validations at the time of Form creation,but here w need to  apply validations again for Grid Controls
 

So lets the First method

First, Open the Default.aspx.cs page

Next,In the Page Load Bind the Grid as follows
protected void Page_Load(object sender, EventArgs e)  
    {  
       try  
        {  
SqlConnection  con = 
new SqlConnection(ConfigurationManager.ConnectionStrings["Testing"].ToString());  
            if (!Page.IsPostBack)  
            {       
                BindData();                  
            }              
        }  
        catch (Exception ex)  
        {  
            lblstatus.Text=ex.message;  
        }  
   }  
     
Next,Create a method BindData()
private void BindData()  
    {  
        try  
        {  
            if (con.State == ConnectionState.Closed)  
            {  
                con.Open();  
            }             
            SqlCommand com = new SqlCommand("select * from Testing ", con);  
            SqlDataAdapter da = new SqlDataAdapter(com);  
            DataSet ds = new DataSet();  
            da.Fill(ds, "Testing");  
            GvTesting.DataSource = ds;  
            GvTesting.DataBind();  
     }  
        catch (Exception ex)  
        {  
            lblstatus.Text = ex.Message;  
        }   
   } 
Next,Apply the Grid Editing Operation

Editing Procedure
protected void GvTesting_RowEditing(object sender, GridViewEditEventArgs e)  
    {  
        try  
        {  
            int id = Convert.ToInt32(GvTesting.DataKeys[e.NewEditIndex].Value);  
            com = new SqlCommand("select * from Testing where TestingId='" + id + "'", con);  
            SqlDataAdapter da = new SqlDataAdapter(com);  
            DataSet ds = new DataSet();  
            da.Fill(ds, "Testing");  
            if (ds.Tables["Testing"].Rows.Count != 0)  
            {  
                DataRow dr = ds.Tables["hulling"].Rows[0];  
                bindItems(dr);  
            }  
        }  
        catch (Exception ex)  
        {  
            lblstatus.Text = ex.Message;  
        }  
    }  
Write the following code to bind the data in Form controls and Hide the submit button and display the Update button

private void bindItems(DataRow dr)  
    {  
        txtName.Text = dr["Name"].ToString();          
        txtSource.Text = dr["Source"].ToString();          
        lblTestingIdId.Text = dr["TestingId"].ToString();  
         btnupdate.Visible = true;  
        btnsubmit.Visible = false;          
    }     
Next,Write the following code to update the data in database
Updating Procedure
protected void btnupdate_Click(object sender, EventArgs e)  
    {  
        try  
        {         
            com = new SqlCommand("Update Testing set Name='"+txtName.Text+"',txtSource='"+txtSource.Text+"' where lblTextingId='"+TestingId+"'",con);  
            com.ExecuteNonQuery();  
            lblstatus.Text = "Record Updated";  
            lblstatus.ForeColor = Color.Green;  
            BindData();  
            btnupdate.Visible = false;  
            btnsubmit.Visible = true;  
        }  
        catch (Exception ex)  
        {  
            lblstatus.Text = ex.Message;  
        }  
    }  
Now, write the following code to delete the record from Testing table
Deletion procedure
protected void GvTesting_RowDeleting(object sender, GridViewDeleteEventArgs e)  
    {  
        try  
        {  
            string id = GvTesting.DataKeys[e.RowIndex].Value.ToString();  
            SqlCommand cmdDelete = new SqlCommand();  
            cmdDelete.CommandText = "Delete Testing where TestingId=" + int.Parse(id);  
            cmdDelete.Connection = con;  
            if (con.State == ConnectionState.Closed)  
                con.Open();  
            cmdDelete.ExecuteNonQuery();  
            con.Close();  
            BindData();  
            lblstatus.Text = "Record Successfully Deleted";  
            lblstatus.ForeColor = Color.Red;  
        }  
        catch (Exception ex)  
        {  
            lblstatus.Text = "Falied to Delete Record";  
            lblstatus.ForeColor = Color.Red;  
        }  
    }  
Next,write the following code to set the index

protected void GvTestingRowCancelingEdit(object sender, GridViewCancelEditEventArgs e)  
    {  
        GvTesting.EditIndex = -1;  

    }    











No comments:

Post a Comment

amazon

Sukanya Samriddhi Account - SBI

SUKANYA SAMRIDDHI Account information by SBI SUKANYA SAMRIDDHI ACCOUNT : FACILITY AVAILABLE AT ALL BRANCHES OF SBI Sukanya Samriddhi ...