我正在努力做到这一点,以便我可以从 SQL Server 获取两条数据到 下拉列表
的 Text Field
中。因此,如果我获得数据 AccountID='1','2'
和 CompanyName='Build it inc','It ltd'
。我希望它显示:
1-Build it inc
2-它有限公司
我可以从 sql 获取数据并将 DataValueField
获取到 AccountID
但我如何显示它。这是我的 aspx。
<asp:DropDownList ID="DDLTemplates" DataValueField="AccountID"
DataTextField='<%#Eval("AccountID") + "-" + Eval("CompanyName")%>'
runat="server"></asp:DropDownList>
我该怎么做?
编辑:因为你们很多人问这里是我的代码背后。感谢所有的帮助
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DDLTemplates.DataSource = GetItems();
DDLTemplates.DataBind();
}
}
public DataSet GetItems()
{
String conn = ConfigurationManager.ConnectionStrings["LiquidusConnectionString"].ConnectionString;
SqlConnection sqlConnection2 = new SqlConnection(conn);
string oString = "Select AccountID, CompanyName from Account";
SqlCommand cmd = new SqlCommand(oString);
cmd.Connection = sqlConnection2;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
sqlConnection2.Open();
da.Fill(ds);
sqlConnection2.Close();
return ds;
}
答案编辑:psoshmo 和 ragerory 找到了我的问题的答案。这是我现在可以使用的代码:
<asp:DropDownList ID="DDLTemplates" DataValueField="AccountID" DataTextField="Company" runat="server"></asp:DropDownList>
代码隐藏:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DDLTemplates.DataSource = GetItems();
DDLTemplates.DataBind();
}
}
public DataSet GetItems()
{
String conn = ConfigurationManager.ConnectionStrings["LiquidusConnectionString"].ConnectionString;
SqlConnection sqlConnection2 = new SqlConnection(conn);
string oString = "SELECT AccountID, (Convert(varchar,AccountId) + ' - ' + CompanyName) as company FROM Account";
SqlCommand cmd = new SqlCommand(oString);
cmd.Connection = sqlConnection2;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
sqlConnection2.Open();
da.Fill(ds);
sqlConnection2.Close();
return ds;
}
希望这对 future 的 googler 有帮助:)
最佳答案
根据您的 GetItems
方法,您可以更改 oString
变量...
string oString = "SELECT AccountID, (Convert(varchar,AccountId) + ' - ' + CompanyName) as Company FROM Account";
然后将您的控件更改为以下内容
<asp:DropDownList ID="DDLTemplates" DataValueField="AccountID" DataTextField="Company" runat="server"></asp:DropDownList>
您要连接这两个字段并使它们成为一个名为 Company
的列,这就是您应该拥有的 TextField。
关于c# - 从 SQL 中获取两个数据字段到下拉列表的文本中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31251101/