2012-06-24 139 views
1

我剛開始學習ASP.Net。昨天晚上,我在網格視圖工作,我通過直接給數據庫命令填充數據。我沒有爲我的網格定義任何模板字段,並且我已將AutoGenerated編輯按鈕設置爲true。數據得到正確顯示,但嘗試處理更新事件我面臨問題,因爲我無法檢索我更新的行的單元格值。檢索DataGrid單元格值

我google了很多,但所有用於檢索單元格值的示例都基於模板字段,但在我的情況下,我沒有在設計時定義網格的列。 請幫幫我。

我的代碼如下:(GridView1_RowUpdating方法是給空值,當我檢查通過應用斷點)

private void FillGrid() 
     { 
      SqlConnection con = new SqlConnection("Data Source=.\\sqlexpress;Initial Catalog=TestDatabase;Integrated security=true;"); 
      DataTable dt = new DataTable("Student"); 
      using (SqlDataAdapter adapter = new SqlDataAdapter("select name,age,Fathername,dob from student", con)) 
      { 
       adapter.Fill(dt); 
      } 
      GridView1.DataSource = dt; 
      GridView1.DataBind(); 
     } 
     protected void Button1_Click(object sender, EventArgs e) 
     { 
      FillGrid(); 
     } 

     protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) 
     { 
      //Response.Write("RowDataBoundEvent Occured"+" "+e.Row.RowType+"\n"); 
     } 

     protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) 
     { 
      GridView1.EditIndex = -1; 
      FillGrid(); 
     } 

     protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e) 
     { 
      GridView1.EditIndex = e.NewEditIndex; 
      FillGrid(); 
     } 

     protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e) 
     { 

      string name = GridView1.Rows[e.RowIndex].Cells[2].Text; 
      string age = GridView1.Rows[GridView1.EditIndex].Cells[3].Text; 
      string salary = GridView1.Rows[GridView1.EditIndex].Cells[4].Text; 
     } 

回答

0

退房GridViewUpdateEventArgs.OldValues和GridViewUpdateEventArgs.NewValues。

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e) 
{ 
    string name = e.NewValues[2]; 
    string age = e.NewValues[3]; 
    string salary = e.NewValues[4]; 
} 
+0

先生,我在這種情況下獲得索引超出範圍異常 –

+0

逸岸我得到的0計數e.newvalues字典時,我沒有快速監視它 –

+0

看看這個SO一篇:HTTP: //sackoverflow.com/questions/6641474/why-im-getting-gridviewupdateeventargsnewvalues-and-gridviewupdateeventargsol – alexm