[英]Getting two DataFields from SQL into the Text of a dropdownlist
我試圖做到這一點,以便我可以從 SQL Server 獲取兩條數據到drop down list
的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;
}
希望這有助於未來的 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 的內容。
只需在您的類中創建一個將這些添加在一起的字段,並將其綁定到 DataTextField
就像是:
public string YourFieldNameHere
{
get { return String.Format("{0} - {1}", AccountID, CompanyName); }
}
編輯:假設你有一個類文件設置我不好。 通常,您應該避免在網頁代碼中使用 GetItems() 之類的方法。 如果您必須在另一個頁面中獲取相同的記錄,您最終會復制您的代碼,這是不好的做法。 我建議您考慮設置類文件來處理這樣的選擇語句,以及您可能需要的其他字段和方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.