网格视图Updatearguments不包含新值

时间:2011-01-22 10:09:59

标签: asp.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(GridView1_RowUpdating);
        GridView1.DataKeyNames = new string[] { "id" };
        GridView1.RowEditing += new GridViewEditEventHandler(GridView1_RowEditing);

    }
    else
        Response.Write("fkj");
}

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
    GridViewRow row = GridView1.Rows[e.RowIndex];
    int id = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value);

    string cls = ((TextBox)(row.Cells[2].Controls[0])).Text;
    string nam = ((TextBox)(row.Cells[3].Controls[0])).Text;
    foreach (DictionaryEntry entry in e.NewValues)
    {
        e.NewValues[entry.Key] = Server.HtmlEncode(entry.Value.ToString());
    }
    com = new SqlCommand("Update tblExpt set name='" + nam + "',class='" + cls + "' where id='" + id + "'", con);
    da = new SqlDataAdapter(com);
    GridView1.EditIndex = -1;
    GridView1.DataSource = ds;
    GridView1.DataBind();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
    GridView1.EditIndex = e.NewEditIndex;
    GridView1.DataSource = ds;
    GridView1.DataBind();
}

}

在上面的代码中,当我尝试访问e.new值时抛出超出范围的异常。

正在访问的表包含3个字段id,class,name 请帮忙解决问题。

2 个答案:

答案 0 :(得分:2)

阅读我撰写的关于从gridview(和其他数据控件)中提取数据的博客文章。此外,在.net 4.0中如果使用双向绑定(< #Bind(“”)#>)e.NewValues将被填充。

此处有更多信息:http://weblogs.asp.net/davidfowler/archive/2008/12/12/getting-your-data-out-of-the-data-controls.aspx

答案 1 :(得分:1)

你得到的异常是因为row.Cells [0] .Controls [0]是一个DataControlLinkBut​​ton而不是TextBox。由于我不知道网格的控件布局,您可以搜索文本框。

而不是:

int id = int.Parse(((TextBox)(row.Cells[0].Controls[0])).Text);
如果每行只有一个TextBox,请执行以下代码:

TextBox box = (TextBox)row.Cells[0].Controls.OfType<TextBox>().First();
int id = int.Parse( box.Text );

如果您有嵌套的html和层次结构,请查看此SO question以嵌套搜索控件