将页面后面的一个代码中使用的方法重用到页面后面的另一个代码

时间:2016-11-15 03:24:25

标签: c# asp.net

在我的asp页面中,我有一个从数据库中检索其值的下拉列表。为了检索下拉列表的值,我在页面后面的代码中编写了一个方法。

现在我也在另一个asp页面中使用相同的下拉列表。为此,我将相同的方法写入相应的代码页面,以便从数据库中检索值。

我想知道有什么方法可以重新使用代码隐藏页面所需的方法吗?

例如。产品页面(asp页面)

<tr>
    <td class="va-top">Type:</td>
    <td><asp:ListBox ID="listBox_ProductType" runat="server" Rows="1" Width="300px"></asp:ListBox></td>               
</tr>

aspx页面

public void GetProductBillingType()
{
    try
    {
        DataTable dt = new DataTable();
        listBox_ProductType.ClearSelection();
        DAL_Product_Registration objDAL = new DAL_Product_Registration();
        dt = objDAL.Get_ProductBillingType();
        if (dt != null && dt.Rows.Count > 0)
        {
            foreach (DataRow row in dt.Rows)
            {
                listBox_ProductType.Items.Add(new ListItem(row["billing_sub_type"].ToString(), row["billing_dtls_id"].ToString()));
            }
        }
    }
    catch (Exception ex) { }
}

现在在另一页中,我使用相同的下拉菜单。我也在页面后面的另一个代码中编写相同的方法。

但是有什么方法可以重用aspx页面中使用的方法。

3 个答案:

答案 0 :(得分:2)

尝试将此功能提取到一些其他方法,该方法将相关ListBox作为参数。

例如:

public class Helper
{
    public static void GetProductBillingType(ListBox lb)
    {
       ...
    }
}

在您的aspx代码中:

public void GetProductBillingType()
    {
       Helper.GetProductBillingType(listBox_ProductType);
    }

在另一个aspx页面中:

public void GetOtherBillingType()
    {
       Helper.GetProductBillingType(listBox_OtherType);
    }

答案 1 :(得分:2)

您可以创建一个静态类并将助手代码保存在那里。这样你就不需要重新发明轮子了。创建静态类的原因是您不需要创建用于访问类方法的实例。 这是一个例子。

public static class HelperMethods
{
    public static void GetProductBillingType(ListBox listBox)
    {
        try
        {
            DataTable dt = new DataTable();
            listBox.ClearSelection();
            DAL_Product_Registration objDAL = new DAL_Product_Registration();
            dt = objDAL.Get_ProductBillingType();
            if (dt != null && dt.Rows.Count > 0)
            {
                foreach (DataRow row in dt.Rows)
                {
                    listBox.Items.Add(new ListItem(row["billing_sub_type"].ToString(), row["billing_dtls_id"].ToString()));
                }
            }
        }
        catch (Exception ex) { }
    }
}

现在,只需调用方法即可在其他地方使用此方法。将ListBox传递给要添加数据的参数。

HelperMethods.GetProductBillingType(list_box_where_you_want_to_add_data);

答案 2 :(得分:0)

这个问题的要点是将可重用的代码部分提取到另一个类(如实用程序或辅助类)中的方法中,并从这些代码behing页面访问此方法。此外,您可以使用像resharper这样的工具来推荐您如何更好地编码。