【问题标题】:dynamic gridview column autocalculation动态gridview列自动计算
【发布时间】:2011-05-31 18:05:41
【问题描述】:

我有一个 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 列自动计算值。公式应为 (grosswt-tarewt)/1000。但我不知道该怎么做。有任何想法吗??

【问题讨论】:

    标签: c# asp.net gridview


    【解决方案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
        }
    }
    

    试试这个

    【讨论】:

    • 我想过这个......但这最初不会从文本框中获取空值吗?以及如何在没有回发的情况下显示计算值?
    • 它在行数据绑定上计算它们,它正在工作。试试看.... 绑定行后会触发,所以没有空值。它不需要回发!
    【解决方案2】:

    假设用户编辑了这些值,您可以将自己的处理程序添加到 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;
            }
         }
    

    【讨论】:

    • 嘿阿德里安...我无法将我的单元格值转换为 int,上面的代码有错误
    • 为我工作。您确定单元格中的值可以转换为整数吗?当您创建 gridview 的单元格时,您应该为它们分配正确的格式,以便只能输入整数。 (CellValidated 仅在值有效时被调用)
    猜你喜欢
    • 2018-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-30
    • 1970-01-01
    • 2022-10-21
    • 1970-01-01
    相关资源
    最近更新 更多