Welcome Anonymous

Monday, September 20, 2010

How to edit GridView manually

Filling, Editing, Updating, Deleting from a GridView is quite easy now.
Just follow these steps.
1. Open Visual Studio create a web based project.
2. Go to design view of Default.aspx page and then drag&drop a GridView control from standard Visual Studio Toolbox.
3.Right click on GridView goto properties and then disable AutoGeneratedColumns property to false.
4. Navigate to your source page (default.aspx).
then we will found the tags look like

asp:gridview id="GridView1" runat="server" autogeneratecolumns="False">

5. Now, open tab in gridview and wirte the following code.

6. Save the File. Now goto your codebehind file(Default.aspx.cs)
7. Replace your Page_Load event with the following

protected void Page_Load(object sender, EventArgs e)
if (!IsPostBack)

8. And write the Grid method

private void fillgrid()
da = new SqlDataAdapter("select * from login", con);
GridView1.DataSource = dt;

9. For GridView Editing Right click on GridView goto events and click in GridViewRowEditing event, it will generates a GridView1_RowEditing method in your codebehind file.
10. Now, in codebehind file write the following code

int i = Convert.ToInt32(e.NewEditIndex);

LinkButton lb1 = (LinkButton)GridView1.Rows[i].FindControl("LinkButton1");
LinkButton lb2 = (LinkButton)GridView1.Rows[i].FindControl("LinkButton2");
LinkButton lb3 = (LinkButton)GridView1.Rows[i].FindControl("LinkButton3");
lb2.Visible = lb3.Visible = true;
lb1.Visible = false;
Label l1 = (Label)GridView1.Rows[i].FindControl("Label1");
Label l2 = (Label)GridView1.Rows[i].FindControl("label2");
l1.Visible = l2.Visible = false;

TextBox t1 = (TextBox)GridView1.Rows[i].FindControl("TextBox1");
TextBox t2 = (TextBox)GridView1.Rows[i].FindControl("Textbox2");
t1.Visible = t2.Visible = true;

11. For GridViewUpdating right click on gridview goto properties and then events double click on
GridViewUpdating event it'll generates a GridView1_RowUpdating event in your codebehind file.
12. Write the following code in that method

int i = e.RowIndex;
TextBox t1 = (TextBox)GridView1.Rows[i].FindControl("TextBox1");
TextBox t2 = (TextBox)GridView1.Rows[i].FindControl("Textbox2");
SqlCommand cmd = new SqlCommand("update login set name='" + t1.Text + "' where psw='" + t2.Text + "'",con );
t1.Visible = t2.Visible = false;


Label l1 = (Label)GridView1.Rows[i].FindControl("Label1");
Label l2 = (Label)GridView1.Rows[i].FindControl("label2");
l1.Visible = l2.Visible = true;


That's it !! It is that much easy to EDITING GRIDVIEW MANUALLY.
Lets' try to start your own logic to modify GridView

No comments:

Post a Comment