2011-01-22 74 views
1
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(); 
} 

}網格視圖Updatearguments不包含新值

在上面的代碼時,我嘗試訪問e.new值索引超出範圍的異常被拋出。

被訪問的表包含3個字段id,class,名稱 請幫助解決問題。

+0

務必閱讀下面balso幫助ühttp://bytes.com/topic/net/answers/579772-gridview-update-cannot-retrieve-new-values – Learner 2011-01-24 13:47:08

回答

1

你得到的異常是因爲row.Cells [0] .Controls [0]是一個DataControlLinkBut​​ton而不是一個TextBox。由於我不知道網格的控件佈局,因此可以搜索您的文本框。

相反的:

int id = int.Parse(((TextBox)(row.Cells[0].Controls[0])).Text); 

做類似下面的代碼,如果有每行只有一個文本框:

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

如果你嵌套了HTML和層次結構嵌套搜索看看這個SO question的控件

+0

來獲取文本Box OfType應該寫成TextBox No? – Learner 2011-01-22 14:35:49

+0

固定:)複製粘貼錯誤 – 2011-01-22 15:18:53