gpt4 book ai didi

c# - 将一个代码隐藏页面中使用的方法重用到另一个代码隐藏页面

转载 作者:行者123 更新时间:2023-11-30 15:20:11 25 4
gpt4 key购买 nike

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

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

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

例如。产品页面(asp page)

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

最佳答案

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

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

关于c# - 将一个代码隐藏页面中使用的方法重用到另一个代码隐藏页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40601486/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com