Swinkaran
Это и есть то самое Asp.Net способ работы в веб-форме,
Умолчанию.aspx-файл
<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="DDList_Demo._Default" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<div class="row">
<div class="col-md-4">
<h2>Positions</h2>
<p>
<asp:DropDownList ID="ListPosition" runat="server">
</asp:DropDownList>
</p>
</div>
</div>
</asp:Content>
Умолчанию.aspx-файл.в CSpublic partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Dictionary<String, String> Positions = ReadData();
ListPosition.DataSource = Positions;
ListPosition.DataTextField = "Value";
ListPosition.DataValueField = "Key";
ListPosition.DataBind();
}
}
private static Dictionary<String, String> ReadData()
{
Dictionary<String, String> Positions = new Dictionary<string, string>();
string ConnString = ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;
using (SqlConnection connection = new SqlConnection(ConnString))
{
string query = "SELECT [EmployeeId] ,[Position] FROM[EmployeeDb].[dbo].[TblEmployees]";
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Connection = connection;
connection.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
Positions.Add(sdr["EmployeeId"].ToString(), sdr["Position"].ToString());
}
}
connection.Close();
}
}
return Positions;
}
}
}
Richard Deeming
Вот в чем дело старый Форм способом. :)
Новый способ будет заключаться в использовании привязка модели[^]:
<asp:DropDownList ID="ListPosition" runat="server"
DataTextField="Value"
DataValueField="Key"
SelectMethod="ReadData"
/>
public Dictionary<string, string> ReadData() { ... }