Edit/Update/Delete Asp.net GridView Progammiclly

Saturday, September 19, 2009




Updating GridView in Asp.net 3.5 is Very Esey Let Do it
1: Program \Visual Studio 2008 and Create NewSite


2 Drag n Drop GridView on Form


3. Right Click on Gridview and Select Properties and in properties Window Select Event



4 double click on form and past on on load Event

if (IsPostBack != true)

{

OleDbDataAdapter da = new OleDbDataAdapter("Select * from MapLayers", cn);

DataSet ds = new DataSet();

da.Fill(ds);

GridView1.DataSource = ds.Tables[0];

GridView1.DataBind();

}

5 and on gridview updating event past this code

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)

{

string layername = null;

string LayerId = null;

try

{

OleDbDataAdapter da = new OleDbDataAdapter("Select * from MapLayers", cn);

DataSet ds = new DataSet();

da.Fill(ds);

DataRow row = ds.Tables[0].NewRow();

row[0] = ((TextBox) GridView1.Rows[e.RowIndex].FindControl("Textbox1")).Text;

row[1]= ((Label)GridView1.Rows[e.RowIndex].FindControl("Label1")).Text;

ds.Tables[0].Rows[e.RowIndex][0] = row[0];

Response.Write(((TextBox)GridView1.Rows[e.RowIndex].FindControl("Textbox1")).Text.ToString());

OleDbCommandBuilder builder = new OleDbCommandBuilder(da);

da.Update(ds.GetChanges());

ds.AcceptChanges();

GridView1.EditIndex = -1;

GridView1.DataSource = ds.Tables[0];

GridView1.DataBind();

ClientScript.RegisterStartupScript(GetType(), "Message", "");

}

catch { }

}


6 add code on gridview Editing event

protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)

{

GridView1.EditIndex = e.NewEditIndex;

}

7 add code on gridview Deleting Event

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)

{

OleDbDataAdapter da = new OleDbDataAdapter("Select * from MapLayers", cn);

DataSet ds = new DataSet();

da.Fill(ds);

DataRow row = ds.Tables[0].NewRow();

ds.Tables[0].Rows[e.RowIndex].Delete();

OleDbCommandBuilder builder = new OleDbCommandBuilder(da);

da.Update(ds.GetChanges());

ds.AcceptChanges();

GridView1.DataSource = ds.Tables[0];

GridView1.DataBind();

GridView1.EditIndex = -1;

//Reset Edit Index

ClientScript.RegisterStartupScript(GetType(), "Message", "");

}

8. Set GridView autogenerateColumns propertie to false

9 add to 3Colums in GridView

Column 1 CommandColumn

Column 2 boundfield

Column 3 boundfield

10 Covert Boundfeild Columns into TemplateField

11 have Fun run Application

thank

download Source Code

By Usama Wahab khan



share this post
Share to Facebook Share to Twitter Share to Google+ Share to Stumble Upon Share to Evernote Share to Blogger Share to Email Share to Yahoo Messenger More...

0 comments: