Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/297.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从ASP.NET DropDownList绑定选定值_C#_Asp.net_Drop Down Menu_Bind - Fatal编程技术网

C# 从ASP.NET DropDownList绑定选定值

C# 从ASP.NET DropDownList绑定选定值,c#,asp.net,drop-down-menu,bind,C#,Asp.net,Drop Down Menu,Bind,在.aspx页面中绑定文本框的值时,我在ListView中执行以下操作: 如何以相同的方式绑定DropDownList中的值 <asp:DropDownList ID="TestDropDownList" runat="server"> <asp:ListItem Value="Test 1">Test 1</asp:ListItem> <asp:ListItem Value="Test 2">Test 2</asp:ListI

在.aspx页面中绑定文本框的值时,我在ListView中执行以下操作:

如何以相同的方式绑定DropDownList中的值

<asp:DropDownList ID="TestDropDownList" runat="server">
   <asp:ListItem Value="Test 1">Test 1</asp:ListItem>
   <asp:ListItem Value="Test 2">Test 2</asp:ListItem>
</asp:DropDownList>

测试1
测试2

要绑定到DropDownList,您需要将数据源绑定到DropDownList控件,并在该阶段指定文本和值,如下所示:

cmd SqlCommand = new SqlCommand("Your SQL Command Here", conn);

TestDropDownList.DataSource = cmd.ExecuteReader();
TestDropDownList.DataTextField = "Name";
TestDropDownList.DataValueField = "Value";
TestDropDownList.DataBind();
这相当于你试图做这样的事情:

<asp:DropDownList ID="TestDropDownList" runat="server">
   <asp:ListItem Value="<%# Bind("Value") %>"><%# Bind("Name") %></asp:ListItem>
</asp:DropDownList>

要绑定到DropDownList,您需要将数据源绑定到DropDownList控件,并在该阶段指定文本和值,如下所示:

cmd SqlCommand = new SqlCommand("Your SQL Command Here", conn);

TestDropDownList.DataSource = cmd.ExecuteReader();
TestDropDownList.DataTextField = "Name";
TestDropDownList.DataValueField = "Value";
TestDropDownList.DataBind();
这相当于你试图做这样的事情:

<asp:DropDownList ID="TestDropDownList" runat="server">
   <asp:ListItem Value="<%# Bind("Value") %>"><%# Bind("Name") %></asp:ListItem>
</asp:DropDownList>


我不知道如何从代码隐藏添加数据源?还有,我如何以这种方式添加多个ListItems?@user1121487-请参见编辑,我已经包含了关于如何创建数据源的更多信息。我不知道如何从代码隐藏中添加数据源?还有,如何以这种方式添加多个列表项?@user1121487-请参阅编辑,我已经介绍了有关如何创建数据源的更多信息