gpt4 book ai didi

c# - 将数据库中的数据绑定(bind)到 .NET 中的下拉列表

转载 作者:太空宇宙 更新时间:2023-11-03 18:15:37 25 4
gpt4 key购买 nike

我遵循 3 层架构,所以我不想像这样在 aspx 页面中附加数据源:

<asp:DropDownList ToolTip="Select User" ID="users" runat="server" 
DataSourceID="SqlDataSource1" DataTextField="CURRENCY_SHORT_DESCRIPTION"
DataValueField="CURRENCY_SHORT_DESCRIPTION" Width="100px">
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
ProviderName="<%$ ConnectionStrings:ConnectionString.ProviderName %>"
SelectCommand="SELECT DISTINCT &quot;Usernames&quot; FROM &quot;Users&quot;">
</asp:SqlDataSource>

我想在数据层中有一个方法,它调用相同的 SQL 语句并接收回数据,然后我将在业务层中有一个方法,将数据绑定(bind)到下拉列表,如下所示:
private void populateUnitList()
{
unitList.DataSource = DatabaseHandler.getUnitList();
unitList.DataBind();
}

这是我在数据库处理程序中的代码:
public static string getUnitList()
{
DatabaseAdapter dba = DatabaseAdapter.getInstance();
string sqlQuery = ("SELECT DISTINCT Usernames FROM Users");
return dba.queryDatabase(sqlQuery).ToString();
}

我正在使用 C# 和 .NET Framework 4.0。这还不适合我。

更新#3:

它也可以按我的意愿工作,这里是:
//controller class
private void populateCurrencyList()
{
currencyList.DataSource = DatabaseHandler.getCurrencyList();
currencyList.DataTextField = "CURRENCY_SHORT_DESCRIPTION";
currencyList.DataValueField = "CURRENCY_SHORT_DESCRIPTION";
currencyList.DataBind();
}

//db handler class
public static DataTable getCurrencyList()
{
DatabaseAdapter dba = DatabaseAdapter.getInstance();
string sqlQuery = ("SELECT DISTINCT CURRENCY_SHORT_DESCRIPTION FROM CURRENCY");

DataTable dt = new DataTable();
dt.Load(dba.queryDatabase(sqlQuery));
return dt;
}

//controller class, the !IsPostBack prevents duplication of fields
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
populateUnitList();
populateCurrencyList();
}
}

最佳答案

SqlConnection  conn = new SqlConnection("Connectionstring")
SqlCommand cmd = new SqlCommand ();

cmd.CommandText = " Select * From GetUsersID";
cmd.Connection = conn;
conn.Open();
DataTable dt = new DataTable();

dt.Load(cmd.ExecuteReader());
conn.Close();

DropDownList1.DataSource = dt;
DropDownList1.DataTextField = "Name";
DropDownList1.DataValueField = "ID";
DropDownList1.DataBind(); `

您必须提到下拉列表的 DataTextField 和 DataValueField 属性。 DataTextField 是要显示的字段,DataValueField 是该字段的值

关于c# - 将数据库中的数据绑定(bind)到 .NET 中的下拉列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6859248/

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