繁体   English   中英

如何从我们返回数据表C#Web应用程序的方法中返回Null

[英]How To Return Null From The Method Where We Return Data Table C# Web Application

如何从出现错误的情况下返回数据表的方法中返回空表或某些空表,下面给出我的代码,

  public DataTable CostOfKilowat()
        {
            try
            {
                DataTable CostDT = new DataTable();
                int Dollar = Convert.ToInt32(txtCommission.Text);
                CostDT = GetProducts();
                DataTable Costtable = GetCostRate(CostDT, Dollar, "DATE,MTU,POWER,COST,VOLTAGE,PERUNITCOST", "DATE", "Group by ");
                return Costtable;
            }
            catch 
            {
                String script = "<script>alert('Enter Valid Cost')</script>";
                Page.RegisterStartupScript("script", script);
            }
            return ;
        }

希望您的建议...

将最后一行更改为:

return null;

从函数定义中,我假设您想返回一个表,以便可以将该信息绑定到网格或其他东西上?

您是在问如何返回空网格,还是真的想知道如何返回null?

对于空网格,返回所有列名,您只需要确保存储过程(或您进行的任何服务器调用)仍selects所有字段,即使where子句使其不返回任何内容。

然后,您必须更改代码以始终返回表:

public DataTable CostOfKilowat()
{
    DataTable CostDT = new DataTable();
    try
    {
        int Dollar = Convert.ToInt32(txtCommission.Text);
        CostDT = GetProducts();
        DataTable Costtable = GetCostRate(CostDT, Dollar, "DATE,MTU,POWER,COST,VOLTAGE,PERUNITCOST", "DATE", "Group by ");
        return Costtable;
    }
    catch 
    {
        String script = "<script>alert('Enter Valid Cost')</script>";
        Page.RegisterStartupScript("script", script);
    }
    return CostDT;
}

如果您真的想返回null ... um .. return null;

您可以这样进行。

返回新的DataTable();

根据问题注释中的答案添加了另一个简单的答案:

  public DataTable CostOfKilowat()
        {
            try
            {
                DataTable CostDT = new DataTable();
                int Dollar = Convert.ToInt32(txtCommission.Text);
                CostDT = GetProducts();
                DataTable Costtable = GetCostRate(CostDT, Dollar, "DATE,MTU,POWER,COST,VOLTAGE,PERUNITCOST", "DATE", "Group by ");
                return Costtable;
            }
            catch(Exception ex)
            {
                String script = "<script>alert('" + ex.Message + "')</script>";
                Page.RegisterStartupScript("script", script);
                return null;
            }
        }

不知道我是否知道,但这也许就是您想要得到的。

嗨,他是我的写法:

public DataTable CostOfKilowat()
    {
        DataTable Costtable = null;
        try
        {
            int Dollar = Convert.ToInt32(txtCommission.Text);
            DataTable CostDT = GetProducts();
            Costtable = GetCostRate(CostDT, Dollar, "DATE,MTU,POWER,COST,VOLTAGE,PERUNITCOST", "DATE", "Group by ");
        }
        catch 
        {
            String script = "<script>alert('Enter Valid Cost')</script>";
            Page.RegisterStartupScript("script", script);
        }
        return Costtable;
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM