如何动态创建gridview更新事件?

时间:2011-01-21 09:08:44

标签: c# asp.net .net gridview

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;
    }
}

只有当我编辑下一行时,用于进入编辑模式的行才意味着第一行永远不会进入编辑模式。请帮助原因。

2 个答案:

答案 0 :(得分:2)

不是

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

这样做:

GridView1.RowUpdating += new GridViewUpdateEventHandler(abc);

此外,而不是

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

这样做

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

也是x 2,而不是

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

这样做

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

为什么我觉得我在上课?)

答案 1 :(得分:0)

因为你还没有设置处理程序来处理GridView.RowEditing。在你的gridview(在.aspx中)你需要连接一个处理RowEditing的方法。

您的gridview代码将如下所示:

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

您需要添加:

OnRowEditing="nameOfMethodYouWantToFire"

所以它看起来像:

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

nameOfMethodYouWantToFire在你的代码后面(你的C#),它处理事件。像这样:

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