2016-11-15 124 views
3

在我的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页面中使用的方法。

+0

您可以将方法定义为静态类中的静态方法,并且可以从那里调用该方法。合理 ? – lukai

+0

@lukai谢谢你的回答。但是请你可以用一些代码示例来解释你的回复。这将是一个很大的帮助。谢谢! – user4221591

回答

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); 
+0

谢谢!它工作正常。 – user4221591

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); 
    } 
0

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

相关问题