簡體   English   中英

如何動態創建gridview更新事件?

[英]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;
    }
}

僅當我編輯下一行時,該行才進入編輯模式,這意味着第一行從不進入編輯模式。請幫助為什么。

代替

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

為什么我覺得我在教課:)

這是因為您尚未設置處理程序來處理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
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM