1
我已經做了一些經典的ASP,但是對於ASP.NET來說真的很新,所以如果可以的話,請給我一些步驟。asp.net下拉列表代碼跨多個頁面重用
我試圖做的是在不同頁面上的多個表單中重複使用相同的下拉列表代碼。
我有Form1.aspx頁面,它有這樣的:
<asp:DropDownList ID="Vendor" runat="server"
AutoPostBack="True"
onselectedindexchanged="ddlVendor_SelectedIndexChanged">
</asp:DropDownList>
然後隱藏文件Form1.aspx.cs頁面的代碼中有這樣一段生成列表的廠商下拉框。
private void FillVendor()
{
string strConn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT VendorID, VendoName FROM Vendor";
DataSet objDs = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
con.Open();
dAdapter.Fill(objDs);
con.Close();
if (objDs.Tables[0].Rows.Count > 0)
{
Vendor.DataSource = objDs.Tables[0];
Vendor.DataTextField = "VendorName";
Vendor.DataValueField = "VendorID";
Vendor.DataBind();
Vendor.Items.Insert(0, "--Select--");
}
else
{
lblMsg.Text = "No Vendor found";
}
}
可以說如果我有另一個form2.aspx頁面和form2.aspx.cs頁面。此頁面將使用與form1.aspx頁面相同的下拉列表。我不想在form2.aspx和form2.aspx.cs中重新編寫相同的代碼。是否有更好的方式在多個頁面之間重用這些代碼?
由於提前,
將其作爲自定義控件進行開發並重用它? – IrishChieftain
是 - 將可重用代碼提取到[用戶控件](http://msdn.microsoft.com/zh-cn/library/26db8ysc(v = vs.85).aspx) – StuartLC