Learner
Learner

Reputation: 1634

How to create gridview updating event dynamically?

public partial class Gridvw_expt2 : System.Web.UI.Page
{
    SqlCommand com;
    SqlDataAdapter da;
    DataSet ds;
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["gj"].ConnectionString);
    protected void Page_Load(object sender, EventArgs e)
    {          
        com = new SqlCommand("Select * from tblExpt",con);
        da = new SqlDataAdapter(com);
        ds = new DataSet();
        da.Fill(ds);
        if (ds.Tables[0].Rows[0] != null)
        {
            GridView1.AutoGenerateEditButton = true;

            GridView1.DataSource = ds;
            GridView1.DataBind();

            GridView1.RowUpdating += new GridViewUpdateEventHandler(abc);
            GridView1.DataKeyNames = new string[] { "id" };
            GridView1.RowEditing += new GridViewEditEventHandler(bc);
        }    
        else
            Response.Write("fkj");
    }

    protected void abc(object sender, GridViewUpdateEventArgs e)
    {
        Response.Write(e.RowIndex);
    }
    protected void bc(object sender, GridViewEditEventArgs e)
    {
        GridView gv = (GridView)sender;
        gv.EditIndex = e.NewEditIndex;
    }
}

the row used to get in edit mode only if i edit the next row means first row never get in edited mode.Please help why so.

Upvotes: 0

Views: 4547

Answers (2)

Vaibhav Garg
Vaibhav Garg

Reputation: 3716

Istead of

GridView1.Attributes.Add("onrowupdating", "abc");

do this:

GridView1.RowUpdating += new GridViewUpdateEventHandler(abc);

Also, Instead of

GridView1.Attributes.Add("DataKeyNames", "id");

do this

GridView1.DataKeyNames = new string[] { "id" };

Also x 2, Instead of

if (ds.Tables[0].Rows[0].ToString() != null)

do this

if (ds.Tables[0].Rows[0] != null) //.ToString() will cause an exception if it is actuall null

Why do I feel like I am teaching a class :)

Upvotes: 2

m.edmondson
m.edmondson

Reputation: 30882

Its because you haven't set up a handler to handle GridView.RowEditing. On your gridview (in the .aspx) you need to wire up a method which will deal with RowEditing.

You're gridview code will look like:

<asp:GridView ID="GridView1" runat="server">
</asp:GridView>

You need to add:

OnRowEditing="nameOfMethodYouWantToFire"

so it looks like:

<asp:GridView ID="GridView1" runat="server" OnRowEditing="nameOfMethodYouWantToFire">
</asp:GridView>

Where nameOfMethodYouWantToFire is in your code behind (your C#) and it handles the event. Something like this:

protected void nameOfMethodYouWantToFire(object sender, GridViewPageEventArgs e)
  {
    //Your code here
  }

Upvotes: 0

Related Questions