[英]Binding Dropdown List From Code-Behind
I would like to display all my category names in a drop down menu in the latest .net framework. 我想在最新的.net框架的下拉菜单中显示所有类别名称。 So far, all I have is: 到目前为止,我所拥有的是:
<asp:DropDownList ID="DDCategories" runat="server">
<asp:ListItem>
</asp:ListItem>
</asp:DropDownList>
Now I need in Code-Behind to tell the Dropdown that I would like to list all the Name
under [Category]
in my database. 现在,我需要在Code-Behind中告诉下拉列表,我想在数据库的[Category]
下列出所有Name
。 The reason for this is that I am going to create a product in which I would like to choose a category name, but I don't know how to display them in a dropdown. 原因是我要创建一个产品,在其中我想选择一个类别名称,但是我不知道如何在下拉菜单中显示它们。
In case if you are using Linq2Sql or Entity Framework your code will looks like: 如果您使用的是Linq2Sql或Entity Framework,您的代码将如下所示:
DDCategories.DataSource = myDatabaseContext.Category;
DDCategories.DataTextField = "Name";
where Category
is generated collection for your table in DB. 其中为数据库中的表生成了Category
的集合。
While you can certainly do it in code behind, I would suggest to use stored Procedure and pass a parameter to it. 虽然您当然可以在后面的代码中完成此操作,但我建议您使用存储过程并将参数传递给它。 Pull the logic in Stored Procedure which data you want to pull. 在存储过程中拉逻辑要提取的数据。 If that is not sufficient to your needs. 如果这还不足以满足您的需求。 You may use a code like this 您可以使用这样的代码
SqlCommand sc = new SqlCommand();
sc.CommandText = "usp_MyStoredProcedure";
sc.CommandType = CommandType.StoredProcedure;
sc.Connection = conn;
sc.Parameters.Add(AddParam(param1, "@param1"));
DropDwonList DDList = new DropDownList()
DDList = FindControl("DDCategories")
And then execute the stored procedure save the result in DDList data. 然后执行存储过程,将结果保存在DDList数据中。 This is just a start. 这只是一个开始。 Hope it helps. 希望能帮助到你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.