2011-05-31 86 views
0

我有一個GridView,在templatefields中的文本框,我動態地添加列到它。動態gridview列自動加載

protected void grid() 
{ 
    DataTable dt = new DataTable(); 

    dt.Columns.Add(new DataColumn("SerialNumber", typeof(string))); 
    dt.Columns.Add(new DataColumn("Material", typeof(string))); 
    dt.Columns.Add(new DataColumn("Bags", typeof(string))); 
    dt.Columns.Add(new DataColumn("GrossWt", typeof(string))); 
    dt.Columns.Add(new DataColumn("TareWt", typeof(string))); 
    dt.Columns.Add(new DataColumn("NetWt", typeof(string))); 
    dt.Columns.Add(new DataColumn("BillWt", typeof(string))); 

    DataRow dr = dt.NewRow(); 
    dt.Rows.Add(dr); 
    dr["SerialNumber"] = 1; 

    GridView1.DataSource = dt; 
    GridView1.DataBind();      
} 

我需要有NetWt列有使用GrossWt和TareWt列autocalulated值。公式應該是(grosswt-tarewt)/ 1000。但我不知道如何去做。有任何想法嗎??

回答

1
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e){ 
    if (e.Row.RowType == DataControlRowType.DataRow) 
    { 
     e.Row.Cells[5] = (e.Row.Cells[3].Text - e.Row.Cells[4].Text)/1000 
    } 
} 

試試這個

+0

我想過這個...但不會這從文本框最初的空值?以及它將如何顯示沒有回傳的計算值? – RAHUL 2011-05-31 10:00:01

+0

它在行數據綁定上計算它們,它正在工作。試試吧......它會在行被綁定後觸發,所以它沒有空值。它不需要回發! – 2011-05-31 10:01:07

0

假設用戶編輯值,你可以將自己的處理程序添加到CellValidated事件,然後做你的價值觀,如:

myDataGridView.CellValidated += new System.Windows.Forms.DataGridViewCellEventHandler(myDataGridView_CellValidated); 

    [...] 
    private void myGridView_CellValidated(object sender, DataGridViewCellEventArgs e) 
    { 
     if (e.ColumnIndex == myGridView.Columns["GrossWt"].Index){ 
      myGridView.Rows[e.Index].Cells["NewWT"].Value = (
       myGridView.Rows[e.Index].Cells["GrossWT"].Value - 
       myGridView.Rows[e.Index].Cells["TareWT"].Value) /1000; 
     } 
    } 
+0

好的,謝謝很多傢伙.... – RAHUL 2011-05-31 10:03:29

+0

嘿,adrian ...我無法將我的單元格值轉換爲int,上面的代碼有錯誤 – RAHUL 2011-05-31 10:32:30

+0

適合我。你確定你的單元格中的值可以轉換爲整數嗎?當你創建gridview的單元格時,你應該爲它們指定正確的格式,以便只能輸入整數。 (CellValidated只在值有效時才被調用) – grimmig 2011-05-31 10:39:55